在 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 及更高版本,您必须使用 UNNotificationCenterDelegateUIUserNotifications 已被弃用。 这对于请求通知权限和处理本地通知是正确的,但您会看到application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) 不推荐 developer.apple.com/reference/uikit/uiapplicationdelegate/… 此外,“接收远程通知”是未在UNNotificationCenterdeveloper.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 中接收远程通知的主要内容,如果未能解决你的问题,请参考以下文章

应用程序在后台时的远程推送通知 swift 3

在 iOS (swift) 应用中,第二个 Firebase 应用的注册无法接收远程通知

在 Swift 中注册远程通知时未收到设备令牌

远程通知中的自定义声音 iOS 10,swift 3

火力基地 |远程通知不显示,swift 3.0

Swift 3 Firebase 远程通知未在 TestFlight 上显示