Ios 将KVO从推送扩展触发到应用
我正在尝试在主应用程序中实现KVO,并观察扩展何时更改了值。 主应用程序在收到推送时打开,但主应用程序中没有触发器。只有当我关闭并打开它时,我才能看到变化 通知类别:Ios 将KVO从推送扩展触发到应用,ios,swift,apple-push-notifications,key-value-observing,Ios,Swift,Apple Push Notifications,Key Value Observing,我正在尝试在主应用程序中实现KVO,并观察扩展何时更改了值。 主应用程序在收到推送时打开,但主应用程序中没有触发器。只有当我关闭并打开它时,我才能看到变化 通知类别: class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationCo
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestAttemptContent = bestAttemptContent {
var user = (bestAttemptContent.userInfo["user"] as! String?)!
let userDefaults = UserDefaults(suiteName: "group.com.test.apps")
userDefaults!.set(user as String, forKey: "User")
userDefaults!.synchronize()
contentHandler(bestAttemptContent)
}
}
}
主视图控制器:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let userDefaults = UserDefaults(suiteName: "group.com.test.apps")
userDefaults!.addObserver(self, forKeyPath: "User", options: NSKeyValueObservingOptions.new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//Not triggered
let userDefaults = UserDefaults(suiteName: "group.com.test.apps")
let user = userDefaults!.string(forKey: "User")
NSLog("User \(user)")
}
}
您是否使用iOS 10或更高版本?跨进程(如扩展)的KVO直到10时才起作用,搜索“Key-Value Observing and NSUserDefaults”套件的
UserDefault
不是共享实例,因此您必须保留它,否则它将被释放
这里是固定的应用程序端控制器。使用Xcode 11.4/iOS 13.4进行测试
注意:KVO只有在设置了真正的新值时才起作用,因此如果在扩展中您将相等的值设置为UserDefaults,则不会通知观察者
我的目标是13.2,根据苹果的文档,我应该在iOS 10之后工作
class ViewController: UIViewController {
// keep suite instance as member
let userDefaults = UserDefaults(suiteName: "group.com.test.apps")
override func viewDidLoad() {
super.viewDidLoad()
userDefaults!.addObserver(self, forKeyPath: "User", options: [.new], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?,
change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let user = userDefaults!.string(forKey: "User")
NSLog("User \(user)")
}
}