如何拦截来自共享扩展的远程通知?
How to intercept remote notification from the share extension?
在iOS应用中intercept/read/get远程通知我们必须实现UIApplicationDelegate方法:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {}
但是无法intercept/read/get以相同的方式从共享扩展中进行远程通知。
如何像在 iOS 应用程序中那样拦截共享扩展的远程通知?
我找到了解决方法:
a。共享扩展和通知服务扩展应该设置到同一个应用组。可以在此处找到如何操作的参考:Apple: Configuring App Groups & second.
b。添加“mutable-content = true”到 Apple 推送通知。
c。实施通知服务扩展。
d。在 didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) 函数中使用 notificationKey 将通知 userInfo 保存到 UserDefaults。
e。在共享扩展中,为 UserDefaults 的 **notificationKey** 添加 KVO。
private var notificationServices = 1
let group = UserDefaults(suiteName: SGConst.groupIdentifier)
group.addObserver(self, forKeyPath: "notificationKey", options: .new, context: ¬ificationServices)
f。当 ** notificationKey** 的值更新时,获取 userInfo 并根据通知更新视图。
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard context == ¬ificationServices else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
// Update depending on notification.
}
在iOS应用中intercept/read/get远程通知我们必须实现UIApplicationDelegate方法:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {}
但是无法intercept/read/get以相同的方式从共享扩展中进行远程通知。
如何像在 iOS 应用程序中那样拦截共享扩展的远程通知?
我找到了解决方法:
a。共享扩展和通知服务扩展应该设置到同一个应用组。可以在此处找到如何操作的参考:Apple: Configuring App Groups & second.
b。添加“mutable-content = true”到 Apple 推送通知。
c。实施通知服务扩展。
d。在 didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) 函数中使用 notificationKey 将通知 userInfo 保存到 UserDefaults。
e。在共享扩展中,为 UserDefaults 的 **notificationKey** 添加 KVO。
private var notificationServices = 1
let group = UserDefaults(suiteName: SGConst.groupIdentifier)
group.addObserver(self, forKeyPath: "notificationKey", options: .new, context: ¬ificationServices)
f。当 ** notificationKey** 的值更新时,获取 userInfo 并根据通知更新视图。
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard context == ¬ificationServices else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
// Update depending on notification.
}