Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

swift - Sharing data in between apps in IOS

I have a task to share data between apps in the same device. May be both apps can use a shared database on same device. How to share Data between two apps in IOS. Anybody have done it in any way. Please let me know. Thanks

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can turn on App group on your App Project capabilities tab on both of your apps with the same group container ID. "group.com.yourCompanyID.sharedDefaults"

enter image description here

Then you can access the same folder from your apps using the following url:

let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.yourCompanyID.sharedDefaults")!

So if you would like to share a switch state from two different apps you should do it as follow:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var sharedSwitch: UISwitch!
    let switchURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.yourCompanyID.sharedDefaults")!
        .appendingPathComponent("switchState.plist")
    override func viewDidLoad() {
        super.viewDidLoad()
        print(switchURL.path)
        NotificationCenter.default.addObserver(self, selector: #selector(updateSwitch), name: .UIApplicationDidBecomeActive, object: nil)
    }
    func updateSwitch(_ notofication: Notification) {
        sharedSwitch.isOn = NSKeyedUnarchiver.unarchiveObject(withFile: switchURL.path) as? Bool == true
    }
    @IBAction func switched(_ sender: UISwitch) {
        let success = NSKeyedArchiver.archiveRootObject(sender.isOn, toFile: switchURL.path)
        print(success)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...