Swati
Swati

Reputation: 1443

Unable to get FCM token on real device but getting on simulator

I have integrated Firebase cloud messaging in my iOS application without cocoa pods. Firebase analytics is working fine. But FCM token is received on simulator but not real device. On real device I keep getting error

Failed to fetch default token Error Domain=com.firebase.iid Code=501 "(null)"

  1. I have uploaded the .p12 certificates for development and prod on Firebase
  2. I have checked the bundle ID for my app and that on Firebase console
  3. I have Push notification enable on my App ID.

Here is my code

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [FIRApp configure];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:)  name:kFIRInstanceIDTokenRefreshNotification object:nil];
}


- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {

    // For iOS 10 display notification (sent via APNS)
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    // For iOS 10 data message (sent via FCM)
    [FIRMessaging messaging].remoteMessageDelegate = self;

    [application registerForRemoteNotifications];

}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];

}

- (void)tokenRefreshNotification:(NSNotification *)notification {
    // Note that this callback will be fired everytime a new token is generated, including the first
    // time. So if you need to retrieve the token as soon as it is available this is where that
    // should be done.
    NSString *refreshedToken = [[FIRInstanceID instanceID] token];
    NSLog(@"InstanceID token: %@", refreshedToken);

    // Connect to FCM since connection may have failed when attempted before having a token.
    [self connectToFcm];

    // TODO: If necessary send token to application server.
}

- (void)connectToFcm {
    // Won't connect since there is no token
    if (![[FIRInstanceID instanceID] token]) {
        return;
    }

    // Disconnect previous FCM connection if it exists.
    [[FIRMessaging messaging] disconnect];

    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"Unable to connect to FCM. %@", error);
        } else {
            NSLog(@"Connected to FCM. FCM token - %@", [[FIRInstanceID instanceID] token] );
        }
    }];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    [FBSDKAppEvents activateApp];

    [self connectToFcm];

}

- (void)applicationDidEnterBackground:(UIApplication *)application {

    [[FIRMessaging messaging] disconnect];
    NSLog(@"Disconnected from FCM");

}

Please help.

Upvotes: 4

Views: 9689

Answers (4)

Godwin
Godwin

Reputation: 638

Non of the above worked for because I needed to ask for the user permission before getting the token.

Future<void> getToken2() async {
try {
  FirebaseMessaging messaging = FirebaseMessaging.instance;
  NotificationSettings settings = await messaging.requestPermission(
    alert: true,
    badge: true,
    sound: true,
  );

  // Check if permission is granted
  if (settings.authorizationStatus == AuthorizationStatus.authorized) {
    String? token = await messaging.getToken();
    print("fcm token: $token");
  } else {
    if (kDebugMode) {
      print('Permission denied');
    }
  }
} catch (e) {
  if (kDebugMode) {
    print('Error getting token: $e');
  }
}

}

Upvotes: 0

GIJoeCodes
GIJoeCodes

Reputation: 1850

Swati's answer above pointed me to a solution. I have tried restarting the device several times not to mention various rewrites of my code. Swati said her device's date was wrong, in my case, I use NordVPN. I paused the service, ran the project, and the FCMToken was printed and uploaded to my database.

Upvotes: 2

Jana iOS
Jana iOS

Reputation: 13

May be the issue is due the version problem.Actually me also faced the same problem.I got the FCM token on simulator but not on the device.The reason is due to registering the User notifications setting on didFinishLaunchingWithOptions..... We have to check the version on both device and simulator... If both are not same..please check the " [[UIApplication sharedApplication] registerUserNotificationSettings:settings] " conditions for the current device version... Bcz I restricted this for >= 10 versions in didFinishLaunchingWithOptions....

Upvotes: 0

Swati
Swati

Reputation: 1443

I got solution to my own problem. The device's date and time was incorrect. The second I changed it to current date & time, Firebase started giving me FCM token and got connected properly. I have checked the push notification as well from Firebase Notification Console. It is working in a way better than I imagined.

Upvotes: 4

Related Questions