简体   繁体   English

在IOS中的应用程序之间共享数据

[英]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. 如何在IOS中的两个应用程序之间共享数据。 Anybody have done it in any way. 任何人都以任何方式做到了。 Please let me know. 请告诉我。 Thanks 谢谢

You can turn on App group on your App Project capabilities tab on both of your apps with the same group container ID. 您可以在具有相同组容器ID的两个应用程序的应用程序项目功能选项卡上打开应用程序组。 "group.com.yourCompanyID.sharedDefaults" “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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM