Firebase push notification doesn't work after a few weeks - ios

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

Related

Firebase Cloud Messaging is not working on iOS 12

I have set up everything according to https://firebase.google.com/docs/cloud-messaging/ios/client#method_swizzling_in
However, I am not receiving any messages.
My APN certificate (p.12) expired, I had to add a new APN key (p.8) (I think there is no issue here.)
I am not receiving anything in my log, after the app enters background.
Also, there are no error messages.
I am confused, it used to work on iOS 11.
What is my mistake here?
#implementation AppDelegate
NSString *const kGCMMessageIDKey = #"gcm.message_id";
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(#"APPDIDFINISHLAUNCH called with options: %#", launchOptions);
[FIROptions defaultOptions].deepLinkURLScheme = #"xxxxx";
[FIRApp configure];
[FIRMessaging messaging].delegate = self;
[[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result,
NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Error fetching remote instance ID: %#", error);
} else {
NSLog(#"Remote instance ID token: %#", result.token);
NSString* message =
[NSString stringWithFormat:#"Remote InstanceID token: %#", result.token];
}
}];
if ([UNUserNotificationCenter class] != nil) {
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
} else {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[application registerUserNotificationSettings:settings];
}
[application registerForRemoteNotifications];
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[FIRMessaging messaging].APNSToken = deviceToken;
NSLog(#"ssaging messaging].APNSToke");
}
- (void)messaging:(FIRMessaging *)messaging didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage {
NSLog(#"didReceiveMessage: %#", remoteMessage);
}
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:#"token"];
[[NSNotificationCenter defaultCenter] postNotificationName:
#"FCMToken" object:nil userInfo:dataDict];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
completionHandler(UIBackgroundFetchResultNewData);
}
I am happy for any help.

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 messaging method swizzling not working

Hi I'm implement FCM (Fire base cloud messaging). I have made the app to receive notification and data from FCM console. I have both my server notification and firebase notification. I want to handle 2 type of notification (from my server and from FCM) separately. I have gone through the docs and this can be achieve by swizzling the notification handler in AppDelegate
But the problem is I can only get FCM message data (IOS 10) in
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {}
and
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {}
The callback for FCM delegate
// The callback to handle data message received via FCM for devices running iOS 10 or above.
- (void)applicationReceivedRemoteMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage {
// Print full message
NSLog(#"Can get here firebase?%#", [remoteMessage appData]);
}
the above callback is never called
How can we use swizzling to sett up FCM handler message separately?
Here is my Appdelegate didfinishlaunchingwith option
application.applicationIconBadgeNumber = 0;
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];
// [START configure_firebase]
[FIRApp configure];
// [END configure_firebase]
// Add observer for InstanceID token refresh callback.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(tokenRefreshNotification:)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
_rootViewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
[self.window setRootViewController:_rootViewController];
[self.window makeKeyAndVisible];
NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (remoteNotification)
[self handleRemoteNotification:remoteNotification shouldPrompt:NO];
self.isFirstTime = true;
self.isJustForRefresh = 0;
return YES;
Anyone know how to make it work?
Edit: here is my observer observation function and didregisterRemoteNotification function
// [START refresh_token]
- (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.
}
// [END refresh_token]
// [START connect_to_fcm]
- (void)connectToFcm {
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Unable to connect to FCM. %#", error);
} else {
NSLog(#"Connected to FCM.");
}
}];
}
// [END connect_to_fcm]
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
NSString *sanitizedDeviceToken = [[[[deviceToken description]
stringByReplacingOccurrencesOfString:#"<" withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString:#" " withString:#""];
DLog(#"sanitized device token: %#", sanitizedDeviceToken);
[PushNotificationManager API_registerAPNSToken:sanitizedDeviceToken
onCompletion:^(BOOL success, NSError *error){}];
[[FIRInstanceID instanceID]setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
}
Updated: I have include this function but still not working
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
if (userInfo[#"gcm.message_id"] != nil) {
NSLog(#"Should get here FCM?");
[[FIRMessaging messaging]appDidReceiveMessage:userInfo];
}else {
NSLog(#"test fetchCompletion handler: %#",userInfo.description);
}
}
You may take a look of this answer? Seems like you missed the line FIRMessaging.messaging().connect(){....
https://stackoverflow.com/a/40881754/1005570
and also the delegate function..
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// 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.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print(userInfo)
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
}

Firebase InstanceID Token Refresh delay on ios device

I have implemented Firebase Cloud Messaging in my iOS application. Everything seems to work just fine, except one thing, the fact that it takes almost 10 seconds from the app to launch to get the device token refreshed in Firebase.
I have added this code to the application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method in the App Delegate:
[FIRApp configure];
//Add an observer for handling a token refresh callback.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(tokenRefreshCallback:) name:kFIRInstanceIDTokenRefreshNotification object:nil];
And this is the tokenRefreshCallback: method:
- (void)tokenRefreshCallback:(NSNotification *)notification {
NSString *refreshedToken = [[FIRInstanceID instanceID] token];
NSLog(#"InstanceID token: %#", refreshedToken);
if ([[FIRInstanceID instanceID] token] != NULL) {
[[FIRMessaging messaging] subscribeToTopic:#"/topics/news"];
NSLog(#"Subscribed to news topic");
}
//Connect to FCM since connection may have failed when attempting before having a token
[self connectToFirebase];
}
And this is the relevant part of logger:
2016-10-13 14:36:23.844 My-App[1111] <Debug> [Firebase/Core][I-COR000001] Configuring the default app.
2016-10-13 14:36:26.492 My-App[1111:2222222] InstanceID token: (null)
2016-10-13 14:36:32.732 My-App[1111:2222222] InstanceID token: c1kmaskdmj...(the actual device token)
Why is the tokenRefreshCallback: called when the InstanceID is (null)?
Why does it take almost 10 seconds before an actual token is retrieved?
In my case. I had the same problem when using deeplinking to navigate between screens.
Without that all was working good.
this was working for me. In application didFinishLaunchingWithOptions I call [self configureFirebase];
- (void)configureFirebase {
[FIRApp configure];
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].delegate = self;
// For iOS 10 data message (sent via FCM)
[FIRMessaging messaging].remoteMessageDelegate = self;
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
also I implement this messages:
// [START receive_message]
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
if (!(application.applicationState == UIApplicationStateActive)) {
[AuthenticationController showAuthenticationViews:self.window];
}
[self readNotification:userInfo];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
[self readNotification:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
}
// [END receive_message]
// [START ios_10_message_handling]
// Receive displayed notifications for iOS 10 devices.
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Handle incoming notification messages while app is in the foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
NSDictionary *userInfo = notification.request.content.userInfo;
[self readNotification:userInfo];
completionHandler(UNNotificationPresentationOptionNone);
}
// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
NSDictionary *userInfo = response.notification.request.content.userInfo;
[self readNotification:userInfo];
completionHandler();
}
#endif
// [END ios_10_message_handling]
// [START ios_10_data_message_handling]
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Receive data message on iOS 10 devices while app is in the foreground.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
// Print full message
//NSLog(#"%#", remoteMessage.appData);
}
#endif
// [END ios_10_data_message_handling]
// [START refresh_token]
- (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.
}
// [END refresh_token]
// [START connect_to_fcm]
- (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 {
[[FIRMessaging messaging] subscribeToTopic:notificationTopic];
//NSLog(#"Connected to FCM.");
}
}];
}
// [END connect_to_fcm]
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
// NSLog(#"Unable to register for remote notifications: %#", error);
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the InstanceID token.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// NSLog(#"APNs token retrieved: %#", deviceToken);
// With swizzling disabled you must set the APNs token here.
// [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
BOOL automatic = [[[NSUserDefaults standardUserDefaults] objectForKey:#"automaticLogin"] boolValue];
if (!automatic) {
[[NSUserDefaults standardUserDefaults] setObject:#(YES) forKey:#"automaticLogin"];
[self moveToInit];
}
}
// [START connect_on_active]
- (void)applicationDidBecomeActive:(UIApplication *)application {
[self connectToFcm];
}
// [END connect_on_active]
// [START disconnect_from_fcm]
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[FIRMessaging messaging] disconnect];
// NSLog(#"Disconnected from FCM");
}
// [END disconnect_from_fcm]
#pragma mark - Process notifications
- (void)readNotification:(NSDictionary *)userInfo {
//read your notification
}
-(void)readLaunchWithOptions:(NSDictionary*)launchOptions{
if (launchOptions[notificationKey]) {
[self readNotification:launchOptions[notificationKey]];
}
}

Firebase ios notification token not generated in objective c

I completed all the steps followed by firebase notification document, finally when I run the app.showing the following error, how to generate device token? please refer screenshot below
Error:
Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
I tried this code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:156.0/255.0 green:39.0/255.0 blue:176.0/255.0 alpha:1.0]];
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
}
[FIRApp configure];
// Add observer for InstanceID token refresh callback.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(tokenRefreshNotification:)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
// [[UIApplication sharedApplication] registerForRemoteNotifications];
[[UIApplication sharedApplication] unregisterForRemoteNotifications];
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// 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];
NSLog(#"Disconnected from FCM");
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// 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.
[self connectToFcm];
}
- (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.
}
// With "FirebaseAppDelegateProxyEnabled": NO
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[[FIRInstanceID instanceID] setAPNSToken:deviceToken
type:FIRInstanceIDAPNSTokenTypeSandbox];
}
- (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"]);
// Pring full message.
NSLog(#"%#", userInfo);
}
- (void)connectToFcm {
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Unable to connect to FCM. %#", error);
} else {
NSLog(#"Connected to FCM.");
}
}];
}
console screenshot:

Resources