我在 Swift服务扩展中遇到了一些大问题:我在应用中添加了一个Notification Service Extension
。通知一到达,扩展的 didReceive 函数就会被调用。
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
// my code
}
我想将诸如String变量之类的数据传递给我的主应用程序 AppDelegate ,但到目前为止我还没有运行。
在上面的 didReceive调用中将数据保存到UserDefaults中是可行的,但是在每种情况下在 AppDelegate 中读取此数据都会返回 nil !< / p>
let defaults = UserDefaults(suiteName: "group.mycompany.myapp")
defaults?.set("This is a String", forKey: "myVariable")
还实现了静态功能
static func shared() -> AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
在应用程序委托中并调用
AppDelegate.shared().myVariable = "This is a String";
扩展类中的无效,因为 AppDelegate 似乎不是该扩展的有效属性:我的应用崩溃了!
注意:我已经选中了TargetMembership框,并将require-only-app-extension-safe-api
设置为否。
我完全不知道如何使它正常工作,因此我们将不胜感激。