I am trying to get FCM Token in my app using this code
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM Token: (error)");
}
else if let token = token {
print("(token)");
}
}
And I get my output as below. I don’t know why it gives error first and there is FCM Token after few moments
Error fetching FCM Token: Error Domain=com.google.fcm Code=505 "No APNS token specified before fetching FCM Token"
UserInfo={NSLocalizedFailureReason=No APNS token specified before fetching FCM Token}
APNs token retrieved: 32 bytes
Firebase registration token: Optional("ckoUPFil4UEtrH2wDCrDVZ:APA91bG7fsR4WdxhN6mSwj_pjoKrX9fNW8TDSlIs7YCDCqqMgTjxHp03te4DMcPD4Y2Rrhg3sM9gjcP_QKndTECeVcEDYaQVsGcmxcKxRRQHDOw_IVZYPsoPho3iYJteE74GHsuuIjHg")
2
FCM token request being made before the APNs token is available. Here’s how to resolve the issue:
Steps to Fix the Issue
-
Request APNs Token: Ensure you request the APNs token properly. Implement the didRegisterForRemoteNotificationsWithDeviceToken method to set the APNs token in Firebase Messaging.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Messaging.messaging().apnsToken = deviceToken print("APNs token retrieved: (deviceToken.map { String(format: "%02.2hhx", $0) }.joined())") }
-
Set Up Firebase Messaging Delegate: Implement the MessagingDelegate to handle the FCM token retrieval.
extension AppDelegate: MessagingDelegate { func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) { print("Firebase registration token: (String(describing: fcmToken))") } }
-
Request Push Notification Permission: Ensure you request permission for push notifications.
if granted { DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } }
-
Request FCM Token After APNs Token is Set: Make sure you request the FCM token only after the APNs token is set.
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)") } }