在 IOS 中的应用程序之间共享数据 [英] Sharing data in between apps in IOS
问题描述
我的任务是在同一设备中的应用程序之间共享数据.可能两个应用程序可以在同一设备上使用共享数据库.如何在 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
推荐答案
您可以在具有相同组容器 ID 的两个应用上的应用项目功能"选项卡上打开应用组."group.com.yourCompanyID.sharedDefaults"
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)
}
}
这篇关于在 IOS 中的应用程序之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!