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

Man*_*n S 5 push-notification ios swift unnotificationserviceextension

在我的场景中,我在父 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")
Run Code Online (Sandbox Code Playgroud)

对于用户默认:

var defaults = NSUserDefaults(suiteName: "group.yourappgroup.example")
Run Code Online (Sandbox Code Playgroud)

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

m1s*_*sh0 0

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

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

这里解释一下。

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

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