【问题标题】:Sharing data between an notification service extension and main app在通知服务扩展和主应用程序之间共享数据
【发布时间】:2019-12-01 02:14:40
【问题描述】:

在我的场景中,我在父 iOS 应用和通知服务扩展之间共享数据。我正在使用 Xcode 10.2.1,iOS 部署目标 10.0

我们已经尝试了 NSUserDefaults 和 Keychain 组,它按预期工作。是否有任何其他方式将值(存储模型或数据类型)从通知服务扩展(TargetB)保存到 MainApp(TargetA)。

一旦应用程序处于终止状态,我们已将值附加到模型中并将其保存在钥匙串中。

保存到 Keycahin:

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

对于 USerDefault:

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

我想将数据从目标 B 传输到目标 A。当应用处于非活动状态时?另一个传输或保存数据?请帮帮我?

【问题讨论】:

标签: ios swift push-notification unnotificationserviceextension


【解决方案1】:

也许我没有正确回答问题。

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

Here已经解释过了。

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

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

【讨论】:

    【解决方案2】:

    在您的 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()
    

    【讨论】:

    • 不是存储在路径中是另一种存储方式吗?
    猜你喜欢
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多