FCMToken always null in real device - ios

I am trying to integrate Fireabase notification in iOS for 5 days.
But I can't get the fcmtoken in real device.
It always null.
Here is my code. This code is just from the firebase GitHub sample code.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[FIRApp configure];
[FIRMessaging messaging].shouldEstablishDirectChannel = true;
[FIRMessaging messaging].delegate = self;
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
// iOS 7.1 or earlier. Disable the deprecation warnings.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UIRemoteNotificationType allNotificationTypes =
(UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge);
[application registerForRemoteNotificationTypes:allNotificationTypes];
#pragma clang diagnostic pop
} else {
// iOS 8 or later
// [START register_for_notifications]
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 {
// iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// For iOS 10 display notification (sent via APNS)
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
//[FIRMessaging messaging].delegate = self;
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
// [END register_for_notifications]
}
return YES; }
Adn I know I can get the femtoken on the didRefreshRegistrationToken delegate method.
The method is fired well on the simulator, but never fired on real device.
And after [FIRApp configure], I tried to get the fcmtoken with this method [[FIRInstanceID instanceID] token],but still token is null.
I have done googling as much as I can do, but get the proper answer on the google.
Please help me.
Any help would be appreciate for me

Related

Firebase push notification doesn't work after a few weeks

I am using Firebase Cloud Messaging in my app. It worked fine for a few weeks, but these last two days, it doesn't.
I send the messages from the Firebase Console. I handle the token refresh. What can be the problem?
This is my code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
[self registerForPush];
}
Here is where I register for Push Notifications:
-(void)registerForPush
{
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 {
// iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error)
{
if (error)
{
NSLog(#"\n\n %# \n\n",error.description);
}
NSLog(#"");
}];
// For iOS 10 display notification (sent via APNS)
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
// For iOS 10 data message (sent via FCM)
[FIRMessaging messaging].remoteMessageDelegate = self;
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
Did register for Remote Notifications with Device Token:
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token = [[FIRInstanceID instanceID] token];
NSLog(#"%#", token);
// Add observer to listen for the token refresh notification.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(onTokenRefresh) name:kFIRInstanceIDTokenRefreshNotification object:nil];
if(token)
{
[self subscribeToTopics];
}
}
this the Observer for when firebase refresh token :
- (void)onTokenRefresh
{
// Get the default token if the earlier default token was nil. If the we already
// had a default token most likely this will be nil too. But that is OK we just
// wait for another notification of this type.
NSString *token = [[FIRInstanceID instanceID] token];
if (token)
{
[self subscribeToTopics];
}
}
this is my subscribe to firebase topics :
-(void)subscribeToTopics
{
[[FIRMessaging messaging] subscribeToTopic:#"/topics/ios"];
[[FIRMessaging messaging] subscribeToTopic:#"/topics/all"];
#ifdef DEBUG
[[FIRMessaging messaging] subscribeToTopic:#"/topics/developer_devices"];
#else
[[FIRMessaging messaging] unsubscribeFromTopic:#"/topics/developer_devices"];
#endif
}
Your APNs certificate has probably been revoked for some reason. Try generating a new one and re-uploading it in the firebase console!
https://firebase.google.com/docs/notifications/ios/console-audience#upload_your_apns_certificate

Why Firebase Messaging is not working after reinstalling my iOS app?

I had just implemented correctly Firebase, it worked perfectly until I uninstalled the app and run again from Xcode. From that point it doesn't receive any Firebase notification, neither background or foreground. How can it be possible? All the certificates seem to be ok. Here is my AppDelegate.m:
#import Firebase;
#import FirebaseInstanceID;
#import FirebaseMessaging;
#interface AppDelegate ()
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
UIPageControl *pageControl = [UIPageControl appearance];
pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
pageControl.backgroundColor = [UIColor whiteColor];
// Use Firebase library to configure APIs
[FIRApp configure];
// Managing notifications:
if(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(#"10.0")){
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
if(!error){
[self registerForNotification];
}
}];
} else {
if ([application respondsToSelector:#selector(isRegisteredForRemoteNotifications)]){
// iOS 8 Notifications:
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[application registerForRemoteNotifications];
[self registerForNotification];
} else {
// iOS < 8 Notifications
[application registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
}
}
return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSString * deviceTokenString = [[[[deviceToken description]
stringByReplacingOccurrencesOfString: #"<" withString: #""]
stringByReplacingOccurrencesOfString: #">" withString: #""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"The generated device token string is : %#",deviceTokenString);
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{
NSLog(#"Failed to get token, error: %#", error.description);
}
// To receive notifications for iOS 9 and below.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print message ID.
NSLog(#"Message ID: %#", userInfo[#"gcm.message_id"]);
// Print full message.
NSLog(#"%#", userInfo);
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
[application registerForRemoteNotifications];
}
- (void)registerForNotification {
UIApplication *application = [UIApplication sharedApplication];
// iOs 8 or greater:
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
UIMutableUserNotificationAction *open;
open = [[UIMutableUserNotificationAction alloc] init];
[open setActivationMode:UIUserNotificationActivationModeBackground];
[open setTitle:NSLocalizedString(#"View", nil)];
[open setIdentifier:NotificationActionOpenView];
[open setDestructive:NO];
[open setAuthenticationRequired:NO];
UIMutableUserNotificationCategory *actionCategory;
actionCategory = [[UIMutableUserNotificationCategory alloc] init];
[actionCategory setIdentifier:NotificationCategoryOpenView];
[actionCategory setActions:#[open]
forContext:UIUserNotificationActionContextDefault];
NSSet *categories = [NSSet setWithObject:actionCategory];
UIUserNotificationType types = (UIUserNotificationTypeAlert|
UIUserNotificationTypeSound|
UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings;
settings = [UIUserNotificationSettings settingsForTypes:types
categories:categories];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else if ([application respondsToSelector:#selector(registerForRemoteNotificationTypes:)]) {
// iOs 7 or lesser:
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[application registerForRemoteNotificationTypes:myTypes];
}
}
Thanks!
The code is fine, no errors. It seems like it's a synchronization problem with Google's servers or something. It happened to me and it starts to work after 1 hour of having installed the app.
Just wait :)
Just in case could benefit someone, the missing part was this:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// for development
[[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
// for production
// [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeProd];
}

FIRInstanceID token null thel first time app starts, OK the second time

I am implementing Firebase push notifications on my iOS app.
On didFinishLaunchingWithOptions, I call [FIRApp configure]. It returns nill token the first time the app starts, but if I run the app again, it returns a valid working token.
NSString *refreshedToken = [[FIRInstanceID instanceID] token];
null the first time.
Here's the code in application didFinishLaunchingWithOptions::
- (void)handleFCMregister
{
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 {
// iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
completionHandler:^(BOOL granted, NSError * _Nullable error) {
}
];
// For iOS 10 display notification (sent via APNS)
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
// For iOS 10 data message (sent via FCM)
[[FIRMessaging messaging] setRemoteMessageDelegate:self];
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
[FIRApp configure];
NSString *refreshedToken = [[FIRInstanceID instanceID] token];
DLog(#"refreshedToken ::%#", refreshedToken);
}
How to get a valid token the first time the app starts? What seems to be wrong? Thanks.

Firebase push notification alert sound is not playing in background mode in iOS 10

I am implementing Apple push notification in my native iOS app.
Push notification is implemented via FireBase.
It's working perfect in iOS 9 & earlier.
I am facing one issue in iOS 10. Push notification is working fine for in iOS 10 with other state but When app is in background, sound of my push notification is not playing.
For other state of app , it's all ok.
Only issue with background mode.
Below is my code for Implement push notification.
Insdie
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
Below is Registration code:
////////// FireBase////////////
// Register for remote notifications
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
// iOS 7.1 or earlier. Disable the deprecation warnings.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UIRemoteNotificationType allNotificationTypes =
(UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge);
[application registerForRemoteNotificationTypes:allNotificationTypes];
#pragma clang diagnostic pop
} else {
// iOS 8 or later
// [START register_for_notifications]
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 {
// iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
if( !error ){
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
}];
[[FIRMessaging messaging] setRemoteMessageDelegate:self];
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
// [END register_for_notifications]
}
[FIRApp configure];
// [END configure_firebase]
// Add observer for InstanceID token refresh callback.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(tokenRefreshNotification:)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
Below are the delegate(s) for manage received notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(#"Message ID: %#", userInfo[#"gcm.message_id"]);
NSLog(#"%#", userInfo);
[self manageAppAfterReceiveNotific: userInfo];
completionHandler(UIBackgroundFetchResultNewData);
}
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
NSDictionary *userInfo = response.notification.request.content.userInfo;
[self manageAppAfterReceiveNotific: userInfo];
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
completionHandler(UNNotificationPresentationOptionAlert);
}
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
NSLog(#"%#", [remoteMessage appData]);
[self manageAppAfterReceiveNotific: [remoteMessage appData]];
}
#endif
Below is my PayLoad :
{
aps = {
alert = {
body = "any text";
title = "New Notification";
};
badge = 1;
"content-available" = 1;
sound = default;
};
extra = "{\"childrenId\":\"48\",\"timestamp\":\"1479724388\"}";
"gcm.message_id" = "Message ID";
noteType = "CHECK_OUT";
}
According to firebase document, https://firebase.google.com/docs/cloud-messaging/http-server-ref, you should put "sound" filed into notification message, please refer Table 2a

How to handle iOS remote notification while app is in background

I am working on iOS push notification functionality through apple push notification,right now i am getting proper notification while my app is in background or foreground,but i want to handle remote notification when my app is in background basically when my app is in background it is simply showing alert message from payload.Actually i just want to customize my remote notification.
code:
- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions {
// Override point for customization after application launch.
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
// [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
}
return YES;
}
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(#"Did Register for Remote Notifications with Device Token (%#)", error);
}
- (void)application:(UIApplication )application didRegisterForRemoteNotificationsWithDeviceToken:(NSData )deviceToken {
NSLog(#"Did Register for Remote Notifications with Device Token (%#)", deviceToken);
}
-(void)application:(UIApplication )application didReceiveRemoteNotification:(NSDictionary )userInfo fetchCompletionHandler:(void (UIBackgroundFetchResult))completionHandler
{
NSDictionary * aps=[userInfo valueForKey"aps"];
NSLog(#"did recevie %#",aps);
NSLog(#"userinfo details %#",[aps valueForKey"alert"]);
}
In iOS 10 first you have to set UNUserNotificationCenterDelegate in AppDelegate.h file
#interface AppDelegate : UIResponder <UIApplicationDelegate,CLLocationManagerDelegate,UNUserNotificationCenterDelegate>
After that in AppDelegate.m write code like this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.1) {
// iOS 7.1 or earlier. Disable the deprecation warnings.
UIRemoteNotificationType allNotificationTypes =
(UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge);
[application registerForRemoteNotificationTypes:allNotificationTypes];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
// iOS 8 or later
// [START register_for_notifications]
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)
{
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
[application registerForRemoteNotifications];
} else {
// iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
completionHandler:^(BOOL granted, NSError * _Nullable error) {
}
];
// For iOS 10 display notification (sent via APNS)
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
[[UIApplication sharedApplication] registerForRemoteNotifications];
return YES;
}
Now implement this method for below iOS10 version
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
NSLog(#"Notification received: %#", userInfo);
if( SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO( #"10.0" ) )
{
NSLog( #"iOS version >= 10. Let NotificationCenter handle this one." );
return;
}
NSLog( #"HANDLE PUSH, didReceiveRemoteNotification: %#", userInfo );
else{
handler( UIBackgroundFetchResultNewData );
}
}
Apple introduces these two methods in iOS10 to receive push notifications.
Write these methods also
// Receive displayed notifications for iOS 10 devices.
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
NSDictionary *userInfo = notification.request.content.userInfo;
NSLog(#"%#", userInfo);
completionHandler( UNNotificationPresentationOptionAlert );
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
NSLog(#"Userinfo %#",response.notification.request.content.userInfo);
// completionHandler(UNNotificationPresentationOptionAlert);
}
That's it.
Try this

Resources