如何在 Firebase 中专门检索 FCM 令牌之前的 APN?

问题描述 投票:0回答:1

在遇到错误之前,我使用的是安装了 Firebase 的 Xcode。今天中午 12 点左右,我开始遇到类似这样的错误

APNS device token not set before retrieving FCM Token for Sender ID 'XXXX'. Be sure to re-retrieve the FCM token once the APNS device token is set.

中午12点之前,我完全没有遇到错误

折腾了9个小时,尝试了各种方法,查了很多网站找出确切的错误,调试,甚至还去了各个地方的YouTube,但无法弄清楚错误是从哪里来的。

如果有帮助,我目前正在使用 Xcode 16 和 Firebase 版本 10.27。

对于任何认为自己可以找到答案的人来说,这是代码

这是我不断调试的 AppDelegate 中的

更多背景信息:

  • 我的应用程序在我的 iPhone 15 Pro Max 上运行,并且在出现错误之前运行良好
  • 我启用了后台模式(后台获取、处理、远程通知)
  • 在我的 Firebase 控制台中,我的云消息传送部分中有 APN 密钥
  • 我已将该应用添加到我的 Firebase 服务器
  • 我的代码中有 Google Info.plist
  • 我已为应用程序注册了应用程序认证 (AppCheck) 和 DeviceCheck
    // This method gets called when the app successfully registers for remote notifications and receives a device token from APNs
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
            print("APNs Device Token: \(deviceToken)")

           // Fetch the FCM registration token (this token is used to send push notifications through Firebase)
           Messaging.messaging().token { token, error in
               if let error = error {
                   print("Error fetching FCM registration token: \(error)")
               } else if let token = token {
                   print("FCM registration token: \(token)")
               }
           }
       }

       // This method is called when the app finishes launching
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Initialize Firebase
        FirebaseApp.configure()
        
        // Log app open event (for Firebase Analytics)
        FirebaseAnalytics.Analytics.logEvent(AnalyticsEventAppOpen, parameters: nil)
        
        // Set the delegate for Firebase Messaging
        Messaging.messaging().delegate = self
        
        // Register for remote notifications
        application.registerForRemoteNotifications()
        
        // Request notification authorization from the user
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if granted {
                DispatchQueue.main.async {
                    UIApplication.shared.registerForRemoteNotifications()
                }
            }
        }
        
        // Set UNUserNotificationCenter delegate
        UNUserNotificationCenter.current().delegate = self
        
        return true
    }
    
    
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        if let fcm = Messaging.messaging().fcmToken {
            print("fcm", fcm)
        }
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        handleDailyReportTrigger()
        completionHandler([.banner, .sound, .badge])
    }
ios xcode firebase apple-push-notifications appdelegate
1个回答
0
投票

实施步骤: 在您的 AppDelegate 中注册 APN:将以下代码添加到您的 AppDelegate 以注册远程通知 (APN) 并检索 APN 令牌。

import Firebase
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Firebase configuration
        FirebaseApp.configure()

        // Request permission to use notifications
        requestNotificationAuthorization(application)

        return true
    }

    func requestNotificationAuthorization(_ application: UIApplication) {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if granted {
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            }
        }
    }

    // This method will be called once the user has granted permission and APNs has successfully registered the app
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // Convert APNs token to string
        let apnsToken = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()

        // Print the APNs token (you can send it to your server if needed)
        print("APNs token: \(apnsToken)")

        // Pass the APNs token to Firebase (if FCM token is requested later)
        Messaging.messaging().apnsToken = deviceToken
    }

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

Firebase 和 APNs 集成: 在上述方法 didRegisterForRemoteNotificationsWithDeviceToken 中,在 Firebase 开始处理 FCM 令牌之前检索 APNs 令牌。您可以使用以下方法将 APNs 令牌传递给 Firebase:

Messaging.messaging().apnsToken = deviceToken

在 APNs 令牌之后检索 FCM 令牌: APNs 注册完成后,Firebase 将自动检索 FCM 令牌。您可以按如下方式处理 FCM 令牌:

Messaging.messaging().token { token, error in
    if let error = error {
        print("Error fetching FCM token: \(error)")
    } else if let token = token {
        print("FCM token: \(token)")
    }
}

流程如下:

  1. 您的应用程序首先注册 APN。
  2. 注册后,didRegisterForRemoteNotificationsWithDeviceToken 提供 APNs 令牌。
  3. 您可以将 APNs 令牌传递给 Firebase,使其能够检索 FCM 代币。
  4. 最后,在
    Messaging.messaging().token.
  5. 的完成处理程序中处理FCM令牌

注意:请在上述方法中调整您的其他代码。或者请发表评论会对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.