在通知服务扩展和主应用程序之间共享数据

6
在我的情境中,我正在父iOS应用程序和通知服务扩展之间共享数据。 我使用Xcode 10.2.1,iOS部署目标为10.0。
我们已经尝试了NSUserDefaults和Keychain组,它们按预期工作。是否有其他方法将来自通知服务扩展(TargetB)的值(存储模型或数据类型)保存到MainApp(TargetA)中?
一旦应用程序处于终止状态,我们就将值追加到模型中并将其保存在钥匙串中。
要保存到Keychain:
NotificationAPI.shared.NotificationInstance.append(Notifications(title: messageTitle, message: messageBody,date: Date()))

let notification = NotificationAPI.shared.NotificationInstance

  let value = keychain.set(try! PropertyListEncoder().encode(notification), forKey: "Notification")

关于UserDefaults:

var defaults = NSUserDefaults(suiteName: "group.yourappgroup.example")

我想在应用处于非活跃状态时将数据从目标B传输到目标A。还有其他的传输或保存数据的方法吗?请帮帮我。


尝试这个 https://stackoverflow.com/a/56475317/5084797 - manishsharma93
你可以尝试使用AppGroup来共享数据。 - Animesh
2个回答

0

也许我没有正确理解问题。

您可以通过CoreData在应用程序之间共享数据:

这里有解释。

通常,您需要将扩展和主应用程序添加到一个组中,并将xcdatamodeled文件添加到扩展的目标中。

我认为UserDefaults、Keychain、CoreData、iCloud以及从后端存储数据并由其他应用程序获取数据是您拥有的所有选项。


0

在你的 VC 中添加以下属性。

var typeArray = [DataModelType]()
let path = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.ABC.app")?.appendingPathComponent("type.plist")

你想要分享的数据模型

struct DataModelType: Codable {
    //define properties which you wanna use.
}

为 ViewController 添加扩展

extension ViewController {

    fileprivate func saveData() {
        let encoder = PropertyListEncoder()
        do{
            let dataEncode = try encoder.encode(typeArray)
            try dataEncode.write(to:path!)
        }
        catch{
            print("Error")
        }
    }

    fileprivate func loadData() {
        if let data = try? Data(contentsOf: path!) {
            let decoder = PropertyListDecoder()
            do {
                typeArray = try decoder.decode([DataModelType].self, from: data)
            }
            catch {
                print("Error")
            }
        }
    }

    func fetchDataModel() -> DataModelType {
        loadData()
        return typeArray
    }
}

在您的扩展程序中,无论何时想要访问数据,请添加以下代码。

let viewController = ViewController()
let currentDataModel = viewController.fetchDataModel()

存储路径之外还有其他的存储方式吗? - Manikandan S

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