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

22

我有一个任务需要在同一设备上共享应用程序之间的数据。也许两个应用程序可以在同一设备上使用共享数据库来实现。如何在iOS中在两个应用程序之间共享数据?是否有人以任何方式完成了它?请告诉我。谢谢


请查看此链接。它基于Objective-C,但是相同的概念仍然适用。 - Matt Le Fleur
@Phoen1xUK 我认为那篇文章已经过时了,因为自从iOS 8以来,App组是官方的实现方式。 - neuhaus
我在谈论App组。你实现了吗? - Abhishek
1个回答

32

您可以在两个具有相同组容器 ID 的应用程序的应用程序项目功能选项卡上打开应用程序组。

enter image description here

然后,您可以使用以下 URL 从您的应用程序访问相同的文件夹:

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

如果您想在两个不同的应用程序之间共享开关状态,应按以下方式操作:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接