18

I'm trying to use FCM for notification.
But <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)" occurs so I can't get notification. What's the problem?

At the console,
Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"

and below is my code on Appdelegate

import UIKit
import CoreData
import Alamofire
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var badgeCount : Int = 0;

    enum BasicValidity : String {
        case Success = "basicInfo"
        case Fail = "OauthAuthentificationError"
    }

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.


        let uns: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(uns)
        application.registerForRemoteNotifications()

        FIRApp.configure()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)

        if let token = FIRInstanceID.instanceID().token() {
            sendTokenToServer(token)
            print("token is < \(token) >:")
        }

        return true
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){


        print("didRegisterForRemoteNotificationsWithDeviceToken()")

        // if FirebaseAppDelegateProxyEnabled === NO:
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .Sandbox)

        print("APNS: <\(deviceToken)>")
    }

    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError){

         print("Registration for remote notification failed with error: \(error.localizedDescription)")
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){


        print("didReceiveRemoteNotification()")

        //if FirebaseAppDelegateProxyEnabled === NO:
        FIRMessaging.messaging().appDidReceiveMessage(userInfo)

       // handler(.NoData)

    }

    // [START refresh_token]
    func tokenRefreshNotification(notification: NSNotification) {
        print("tokenRefreshNotification()")
        if let token = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(token)")
            sendTokenToServer(token)
            FIRMessaging.messaging().subscribeToTopic("/topics/global")
            print("Subscribed to: /topics/global")
        }
        connectToFcm()
    }
    // [END refresh_token]

    func sendTokenToServer(currentToken: String) {
        print("sendTokenToServer() Token: \(currentToken)")
        // Send token to server ONLY IF NECESSARY
    }

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

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    // [START disconnect_from_fcm]
    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

       // UIApplication.sharedApplication().applicationIconBadgeNumber = 0
         connectToFcm()

    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }
  • I can get notification from Firebase consol if I send notifications by using bundle ID. But I can't get if our server send notification to specific device with token.
Cœur
  • 37,241
  • 25
  • 195
  • 267
kimpro
  • 329
  • 1
  • 5
  • 13
  • @Frank van Puffelen Could you help me? – kimpro Aug 12 '16 at 08:09
  • Given that you are receiving notifications when you send to the app (bundle id) from the console it means that your app has a valid IID token, but I'm not sure that is the one you are using to send to. If you uninstall the app and reinstall it you may notice several tokens printed, only the last one is valid. I'd also try sending to the topic you are using since that will also confirm that the device has a valid token but you may be using the wrong one. – Arthur Thompson Aug 12 '16 at 21:18
  • @kimpro I'm having the same issue - were you able to find the way how to fix it? Thank you! – Dmitry Sep 26 '16 at 17:02
  • Possible duplicate of [How to fix Failed to fetch default token error?](http://stackoverflow.com/questions/37443334/how-to-fix-failed-to-fetch-default-token-error) – Rachit Rawat Dec 06 '16 at 12:26

2 Answers2

5

For me, I tried following thigs to make it work:

  • Re-Enabling Capabilities->push notification, keychain sharing and background modes->remote notification
  • Reinstalling the app(this will generate new refresh token, it will be same for subsequent runs so might not get printed every time you run the app).
  • Making sure that I have correct .p12 file uploaded in firebase console->project settings->cloud messaging
  • Rechecking provisioning profile in apple developer center(I had to re-activate ios developer provisioning profile.)

You might still get the warning but if you try to send notification from firebase console using the refresh token, it will work.

Rujoota Shah
  • 1,251
  • 16
  • 18
  • where i can find refresh token.tokenRefreshNotification is not being called – Krutarth Patel Jan 02 '17 at 11:20
  • @KrutarthPatel not sure about your question but if your tokenRefreshNotification is not being called, you might need to uninstall and reinstall the app. If you put debug point in that function, it will get called when you after firebase is configured. – Rujoota Shah Jan 12 '17 at 19:03
  • I am getting warning and able to send message with firebase console but my app is not able to launch due to some issue . What to do with that . – Anuj May 02 '18 at 09:59
0

It sounds like the server you're using to deliver the remote notification may have an old record of your FCM token. The Google FCM docs state that the FCM token can be rotated (changed) when:

  • The app is restored on a new device
  • The user uninstalls/reinstall the app
  • The user clears app data.

They quote that its good practice to update your server's record of this token using a delegate callback method:

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    // Send the token to your server here
}

That method wasn't working for me, so I had to update it manually on every app launch (after a delay of about 20-25s as the rotation isn't always instant). You can do this with:

let token = Messaging.messaging().fcmToken  // Send this to your server

After these changes I still get the warning console log message, but push notifications work perfectly every time.

Peza
  • 1,347
  • 1
  • 11
  • 23