ios - 应用程序在后台时未收到 Swift FCM 数据消息 (iOS 10)

标签 ios swift firebase push-notification firebase-cloud-messaging

我浏览了我能找到的每一篇文章,并一遍又一遍地阅读 Firebase 文档,但我找不到错误。我的应用程序在前台时接收 FCM 数据消息,因此没有问题。但是当应用程序在后台运行时,不会收到任何数据。一旦应用程序打开,它甚至不会显示。 消息优先级设置为“高”,“内容可用”设置为 true。我应该收到一堆身份证。 这是我的 AppDelegate 代码(主要来自 FCM 示例代码):

//
//  AppDelegate.swift
//


import UIKit
import UserNotifications

import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    let gcmMessageIDKey = "gcm.message_id"

    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {


        if UserDefaults.standard.bool(forKey: "launched_before") == false {

            self.window = UIWindow(frame: UIScreen.main.bounds)

            let storyboard = UIStoryboard(name: "Settings", bundle: nil)

            let initialViewController = storyboard.instantiateViewController(withIdentifier: "welcomeViewController") as! WelcomeViewController

            self.window?.rootViewController = initialViewController
            self.window?.makeKeyAndVisible()

        } else {

            // Register for remote notifications. This shows a permission dialog on first run, to
            // show the dialog at a more appropriate time move this registration accordingly.
            // [START register_for_notifications]
            if #available(iOS 10.0, *) {

                // For iOS 10 display notification (sent via APNS)
                UNUserNotificationCenter.current().delegate = self
                // For iOS 10 data message (sent via FCM)
                FIRMessaging.messaging().remoteMessageDelegate = self

            } else {
                let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
                application.registerUserNotificationSettings(settings)
            }

            application.registerForRemoteNotifications()

            // [END register_for_notifications]
            FIRApp.configure()


            // Add observer for InstanceID token refresh callback.
            NotificationCenter.default.addObserver(self,
                                               selector: #selector(self.tokenRefreshNotification),
                                               name: .firInstanceIDTokenRefresh,
                                               object: nil)

        }

        return true
    }

    // [START receive_message]
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (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.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)

        print("METHOD 2")

        completionHandler(.newData)
    }


    // [END receive_message]

    // [START refresh_token]
    func tokenRefreshNotification(_ notification: Notification) {
        if let refreshedToken = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
        }

        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }
    // [END refresh_token]

    // [START connect_to_fcm]
    func connectToFcm() {
        // Won't connect since there is no token
        guard FIRInstanceID.instanceID().token() != nil else {
            return;
        }

        // Disconnect previous FCM connection if it exists.
        FIRMessaging.messaging().disconnect()

        FIRMessaging.messaging().connect { (error) in
            if error != nil {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }
    // [END connect_to_fcm]

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Unable to register for remote notifications: \(error.localizedDescription)")
    }

    // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
    // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
    // the InstanceID token.
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")

        // With swizzling disabled you must set the APNs token here.
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)

        FIRMessaging.messaging().subscribe(toTopic: "/topics/substitutions")
        FIRMessaging.messaging().subscribe(toTopic: "/topics/debug")
    }

    // [START connect_on_active]
    func applicationDidBecomeActive(_ application: UIApplication) {
        connectToFcm()
    }
    // [END connect_on_active]

    // [START disconnect_from_fcm]
    func applicationDidEnterBackground(_ application: UIApplication) {
        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }
    // [END disconnect_from_fcm]

    func evaluateRecievedData (remoteMessage: FIRMessagingRemoteMessage) {

    // Evaluate the data...

    }

}

// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let userInfo = notification.request.content.userInfo
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Change this to your preferred presentation option
        completionHandler(.alert)
    }


    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        print("USER HAS PRESSED BANNER")

        // Do some stuff...

        completionHandler()
    }

}
// [END ios_10_message_handling]
// [START ios_10_data_message_handling]
extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices while app is in the foreground.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {

        print(remoteMessage.appData)

        self.evaluateRecievedData(remoteMessage: remoteMessage)

        print("RECIEVED MESSAGE (FOREGROUND)")

    }

}
// [END ios_10_data_message_handling]

我已激活推送通知和后台模式:Info.plist 中的“远程通知”。理想情况下,我想在后台处理数据并向用户发送通知(如果与用户有关)。

发送的数据如下所示:

{
  "to": "\/topics\/substitutions",
  "priority": "high",
  "content_available": true,
  "data": {
    "debug": true,
    "new_ids": [
      7914,
      7915,
      7916,
      7917,
      7918
    ],
    "updated_ids": [

    ]
  }
}

如果有人知道这个问题的解决方案,我将非常感激。

最佳答案

您必须添加通知负载才能在后台接收通知。

{
  "to": "\/topics\/substitutions",
  "priority": "high",
  "content_available": true,
  "data": {
    "debug": true,
    "new_ids": [
      7914,
      7915,
      7916,
      7917,
      7918
    ],
 "notification":{
      "title":"Sample Title",
      "body":"sample body!"
    }
    "updated_ids": [

    ]
  }
}

更多信息About FCM Messages

关于ios - 应用程序在后台时未收到 Swift FCM 数据消息 (iOS 10),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41683565/

相关文章:

iphone - 应用程序在发送和接收特殊字符时崩溃

iphone - ios 应用程序内存不足

ios - Levenshtein 距离算法优于 O(n*m)?

ios - 应用程序中的两个选项卡 Controller

ios - Swift 3 viewDidLoad() - fatal error : unexpectedly found nil while unwrapping an Optional value

ios - 无法在 swift 中使用 "floor"

ios - 转到详细 View Controller

android - 从客户端发送 firebase 云消息而不暴露 API secret

javascript - 如何使用 Cloud Firestore 在 ionic 4 应用程序中获取数据

swift - 在 firestore 上自动更新的计时器