0
votes

I've uploaded development and production certificates on FCM, Enabled push notification in Capabilities, Placed GoogleService-Info.plist in my project. I've tried making another Google account and trying again all the procedure but nothing worked for me.

I tried sending notification to single device token, but it gets rejected showing "Invalid registration token.check token format"

Below is the code I tried.

  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    NSError *configureError;
[[GGLContext sharedInstance] configureWithError:&configureError];
NSAssert(!configureError, @"Error configuring Google services: %@", configureError);



GAI *gai = [GAI sharedInstance];
gai.trackUncaughtExceptions = YES;
gai.logger.logLevel = kGAILogLevelVerbose;

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    UIRemoteNotificationType allNotificationTypes =
    (UIRemoteNotificationTypeSound |
     UIRemoteNotificationTypeAlert |
     UIRemoteNotificationTypeBadge);
    [application registerForRemoteNotificationTypes:allNotificationTypes];
#pragma clang diagnostic pop
} else {

    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
        UIUserNotificationType allNotificationTypes =
        (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings =
        [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0

        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
        UNAuthorizationOptions authOptions =
        UNAuthorizationOptionAlert
        | UNAuthorizationOptionSound
        | UNAuthorizationOptionBadge;
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
        }];


        [FIRMessaging messaging].remoteMessageDelegate = self;
#endif
    }

    [[UIApplication sharedApplication] registerForRemoteNotifications];
}


[FIRApp configure];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:)
                                             name:kFIRInstanceIDTokenRefreshNotification object:nil];
    return YES;


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

[[FIRMessaging messaging] disconnect];

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
[self connectToFirebase];


 application.applicationIconBadgeNumber = 0;
}

- (void) application:(UIApplication *) application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:( void (^)(UIBackgroundFetchResult))completionHandler{

}

#pragma mark -- Custom Firebase code


- (void)tokenRefreshCallback:(NSNotification *) notification{
NSString *refreshedToken = [[FIRInstanceID instanceID] token];

[self connectToFirebase];
}

-(void) connectToFirebase{

[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error)
 {
     if ( error != nil)
     {

     }
     else
     {

     }
 }];
}
- (void)applicationWillResignActive:(UIApplication *)application {}


- (void)applicationWillEnterForeground:(UIApplication *)application {}


- (void)applicationWillTerminate:(UIApplication *)application {}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
if (userInfo[kGCMMessageIDKey]) {

    NSLog(@"%@",userInfo);
}}


 - (void)userNotificationCenter:(UNUserNotificationCenter *)center
   willPresentNotification:(UNNotification *)notification
     withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {

NSDictionary *userInfo = notification.request.content.userInfo;
if (userInfo[kGCMMessageIDKey]) {

}


completionHandler(UNNotificationPresentationOptionNone);
}

 - (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
     withCompletionHandler:(void (^)())completionHandler {
   NSDictionary *userInfo = response.notification.request.content.userInfo;
if (userInfo[kGCMMessageIDKey]) {

}

completionHandler();
  }

- (void)connectToFcm {

if (![[FIRInstanceID instanceID] token]) {
    return;
}

[[FIRMessaging messaging] disconnect];

[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
    if (error != nil) {

    } else {

    }
}];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"PUSH ERROR: %@", error);
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(@"%@",deviceToken);
}

- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {

}

- (void)tokenRefreshNotification:(NSNotification *)notification {

NSString *refreshedToken = [[FIRInstanceID instanceID] token];    
NSLog(@"%@",refreshedToken);

[self connectToFcm];

}

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

[application registerForRemoteNotifications];
}
3
Which token are you using? Are you using device token? - Sivajee Battina
try to send using select app . instead of single device . or ensure that you have upload correct .p12 file in project setting tab. - KKRocks
if you have recently add .p12 then you need to redownload google configuration file and replace with old one. - KKRocks
@SivajeeBattina yes device token. - Shikha Sharma
@KKRocks I tried sending with selecting app too - Shikha Sharma

3 Answers

0
votes

Looks like you are using device token to send push notifications from firebase console. If that's true, you shouldn't use device token. Instead, Firebase will give you FCMRegistration token. Try to use that token to send a notification to that specific device.

Excerpted from my article.

To send a push notification to the particular device we need the device token. When you run the application on your device(Not on a simulator) and if your setup is correct, your console will print Device token and FCM registration token. Both are similar but not the same. Device token we use when we are sending push notifications through some third party services or our own server. We use FCM registration token if we are sending push notifications through firebase console. So in our case, we take FCM registration token which is printed on the console.

enter image description here Below is my article on How to send push notifications using firebase

Additonal Info: In case, if you want to try checking whether your push notifications code configured correctly or not use third party library like Pusher But this time use device token in pusher to check.

0
votes

Might be this is the issue you are faced.

You need to upload correct .p12 file for Your APNS .

You need to simply Goto Project Setting then under Cloud Messaging

Here you need to add your .p12 file.

enter image description here

After uploading you need to redownload configuration file and replace with old one.

Solution 2

I have upload swift code if you can understand then convert it to objective-c because i don't have objective-c code.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
      FirebaseApp.configure()
    if #available(iOS 10.0, *) {
      // For iOS 10 display notification (sent via APNS)
      UNUserNotificationCenter.current().delegate = self

      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()

    return true
  }

func application(_ application: UIApplication,
                   didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken as Data
    var token: String = ""
    for i in 0..<deviceToken.count {
      token += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
    }

    print(token)
  }

In capabilities tab, it should be like also

enter image description here

0
votes

Use This Code:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
    if #available(iOS 10.0, *)
    {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.currentNotificationCenter().delegate = self
        UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert])          { (granted, error) in
                if granted
                {
                //self.registerCategory()
             }
         }
         // For iOS 10 data message (sent via FCM)
         FIRMessaging.messaging().remoteMessageDelegate = self
    }
    else
    {
        let settings: UIUserNotificationSettings =  UIUserNotificationSettings(forTypes: [.Alert,.Badge,.Sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }          
    application.registerForRemoteNotifications()        
    //Configuring Firebase
    FIRApp.configure()
    // Add observer for InstanceID token refresh callback.
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)     
     return true
}

//Receive Remote Notification on Background
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
{
    FIRMessaging.messaging().appDidReceiveMessage(userInfo)
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Prod)
}

func tokenRefreshNotification(notification: NSNotification)
{
    if let refreshedToken = FIRInstanceID.instanceID().token()
    {
            print("InstanceID token: \(refreshedToken)")
    }
    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()
}

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

func applicationDidBecomeActive(application: UIApplication)
{            
    connectToFcm()
}