There are 2-3 reasons behind this.
- Firebase is not configured/initialised at didFinishLaunchingWithOptions
- FCM token get expired or invalid and refresh token observer not added
- Use of invalid/different GoogleService-Info.plist
i.e if your are using 2 GoogleService-Info.plist in same project for Dev and production . so make sure at the time of installing app the correct GoogleService-Info.plist is picking up
pod 'Firebase/Messaging'
if you are using InAppMessagingDisplay too then install this pod also
pod 'Firebase/InAppMessagingDisplay'
initiation of Firebase at didFinishLaunchingWithOptions
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: CGRect(x: 0, y: 0, width: kDeviceWidth, height: kDeviceHeight))
FirebaseApp.configure()
NotificationCenter.default.addObserver(self, selector: #selector(tokenRefreshNotification), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = true
UNUserNotificationCenter.current().delegate = self
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
}
// [START refresh_token]
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
//You save or send fcm token to your sever
}
//+++++++++++++++++++++++
// FCM Token Get Refreshed
@objc func tokenRefreshNotification(_ notification: Notification) {
getFCMToken()
}
private func getFCMToken() {
InstanceID.instanceID().instanceID { (result, error) in
if error == nil {
if let result = result {
let fcmToken = result.token
//Save or send to your server
}
}
}
}