在 Swift 3 中接收远程通知
Posted
技术标签:
【中文标题】在 Swift 3 中接收远程通知【英文标题】:Receiving a Remote Notification in Swift 3 【发布时间】:2017-02-05 20:17:43 【问题描述】:我有以下代码:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
let queryNotification = CKQueryNotification(fromRemoteNotificationDictionary: userInfo)
let notification = Notification(name: NSNotification.Name("Name"), object: nil, userInfo: ["Key": queryNotification])
NotificationCenter.default.post(notification)
但是,有人告诉我这不是接收远程通知的正确方式。相反,我被指示使用以下委托方法。我不明白如何使用这种方法来做我上面所做的事情。有人请帮忙。
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
【问题讨论】:
你是对的。远程通知不会传递到 UNNotificationCenterDelegate 方法 @Paulw11 - 对于 ios 10 及更高版本,您必须使用UNNotificationCenterDelegate
。 UIUserNotifications
已被弃用。
这对于请求通知权限和处理本地通知是正确的,但您会看到application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
不推荐 developer.apple.com/reference/uikit/uiapplicationdelegate/… 此外,“接收远程通知”是未在UNNotificationCenter
developer.apple.com/reference/usernotifications/…的概述中列出
application:didReceiveRemoteNotification:
已弃用,而不是 application:didReceiveRemoteNotification:fetchCompletionHandler:
【参考方案1】:
我认为你想要做的是这样的:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
// Extrapolate userInfo
let userInfo = response.notification.request.content.userInfo
let queryNotification = CKQueryNotification(fromRemoteNotificationDictionary: userInfo)
let notification = Notification(name: NSNotification.Name("Name"), object: nil, userInfo: ["Key": queryNotification])
NotificationCenter.default.post(notification)
completionHandler()
【讨论】:
以上是关于在 Swift 3 中接收远程通知的主要内容,如果未能解决你的问题,请参考以下文章