iOS 无法收到来自 FCM 的通知

Can't receive notifictations from FCM on iOS

我有一个服务器 (Java),它使用 Google 的 FCM 发送消息。 在 Android 上它工作正常我可以收到通知,但由于某些原因在 iOS 上它没有。

这是我的 AppDelegate.swift:

import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications
import GoogleMobileAds

@main
class AppDelegate: UIResponder, UIApplicationDelegate    {
    let gcmMessageIDKey = "my_message_type"

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()
        FirebaseConfiguration.shared.setLoggerLevel(.min)
        GADMobileAds.sharedInstance().start(completionHandler: nil)
        Messaging.messaging().delegate = self
        registerToFirestoreMessaging(application)
                     
        return true
    }

    func registerToFirestoreMessaging(_ application: UIApplication) {
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
          options: authOptions,
          completionHandler: { _, _ in }
        )

        application.registerForRemoteNotifications()
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
            if let messageID = userInfo[gcmMessageIDKey] {
                print("Message ID: \(messageID)")
            }
        Messaging.messaging().appDidReceiveMessage(userInfo)
        print("User Info: \(userInfo)")
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                         fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
            if let messageID = userInfo[gcmMessageIDKey] {
                print("Message ID: \(messageID)")
            }
        print("User Info: \(userInfo)")
        Messaging.messaging().appDidReceiveMessage(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
    }
    
    func application(_ application: UIApplication,
                     didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Unable to register for remote notifications: \(error.localizedDescription)")
    }
    
    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")
        #if PROD_BUILD
        Messaging.messaging().setAPNSToken(deviceToken, type: .prod)
        print("APNs prod token")
        #else
        Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
        print("APNs sandbox token")
        #endif
    }
}


@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    Messaging.messaging().appDidReceiveMessage(userInfo)
    print("User Info: \(userInfo)")
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }
    completionHandler([[.alert, .sound]])
  }

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


extension AppDelegate: MessagingDelegate {
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
    print("Firebase registration token: \(String(describing: fcmToken))")

    let dataDict: [String: String] = ["token": fcmToken ?? ""]
    NotificationCenter.default.post(
      name: Notification.Name("FCMToken"),
      object: nil,
      userInfo: dataDict)
  }
}

我有能力在后台模式下推送通知和远程通知。 我尝试在启用和禁用调配的情况下使用此代码。它没有做任何改变。

感谢阅读。欢迎任何帮助!

没有标题的通知和 body 不应显示在通知窗格中。我期待在通知窗格中看到通知,但服务器发送的通知是静默通知。 为了接受这些通知,您必须在 AppDelegate.swift.

中实施 didReceiveRemoteNotification

我是这样做的:

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                         fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // In my userInfo is the messageID of the notification
        if let messageID = userInfo[gcmMessageIDKey] {
            handleSilentNotification(messageType: messageID as! String)
        }
        // I'm not using swizzling, so I have to notify FCM that a message was received.
        Messaging.messaging().appDidReceiveMessage(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
    }

之后,我发送了一个本地通知,它按预期工作。 感谢所有提供帮助的人!