Swift 和 Firebase Cloud Messaging Notification 仅在应用关闭时有效

Swift and Firebase Cloud Messaging Notification only work when app is colsed

当应用程序关闭时,我有 FCM 通知工作,但当应用程序打开并且 运行 在前台时,我无法让它们正常工作。

我收到以下错误 "Warning: Application delegate received call to -application:didReceiveRemoteNotification:fetchCompletionHandler: but the completion handler was never called." 我已经搜索 google 数小时并阅读了 firebase 文档,但我不确定如何解决此错误。

// [START receive_message]
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                 fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print("%@", userInfo)

    ////new code to help with error but no luck
    if application.applicationState == UIApplicationState.Active {
        print("%@", userInfo)
        print("message recieved")
    }
}

添加以下代码无效

if application.applicationState == UIApplicationState.Active {
        print("%@", userInfo)
        print("message recieved") }

如有任何帮助或建议,我们将不胜感激

您收到此错误 Warning: Application delegate received call to -application:didReceiveRemoteNotification:fetchCompletionHandler: but the completion handler was never called. 因为您没有 return FechedCompletionHandler.

你应该 return 这个 completionHandler 在适当的地方有适当的 UIBackgroundFetchResult 值,UIBackgroundFetchResult 是一个枚举值是:

  • 新数据
  • 无数据
  • 失败

例如,您的 didReceiveRemoteNotification 将变为:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
             fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification

// Print message ID.
print("Message ID: \(userInfo["gcm.message_id"]!)")

// Print full message.
print("%@", userInfo)

////new code to help with error but no luck
if application.applicationState == UIApplicationState.Active {
    print("%@", userInfo)
    print("message recieved")
    completionHandler(.NewData)
}

}