Sharing data in between apps in IOS

♀尐吖头ヾ 提交于 2019-12-17 02:31:58

问题


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


回答1:


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"

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)
    }
}


来源:https://stackoverflow.com/questions/32652795/sharing-data-in-between-apps-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!