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)
}
Related
I am new in iOS I am using firebase for iOS push notification and I am using objective c . According to firebase tutorial I am getting notifications properly back ground and foreground .Now I want registration tokens to make device groups for notifications.So am not getting registration token how can I do that, here is my code.
#import "AppDelegate.h"
#import Firebase;
#import FirebaseMessaging;
#import FirebaseInstanceID;
//#import <FirebaseMessaging/FirebaseMessaging.h>
//#import FirebaseMessaging;
#import UserNotifications;
//#import FirebaseMessaging;
#interface AppDelegate ()<UNUserNotificationCenterDelegate,FIRMessagingDelegate>
#end
#implementation AppDelegate
NSString *const kGCMMessageIDKey = #"gcm.message_id";
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//setup configure
[FIRApp configure];
// [START set_messaging_delegate]
// [FIRMessaging messaging].delegate=self;
// [END set_messaging_delegate]
if ([UNUserNotificationCenter class] != nil) {
// iOS 10 or later
// For iOS 10 display notification (sent via APNS)
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
completionHandler:^(BOOL granted, NSError * _Nullable error) {
// ...
}];
} else {
// iOS 10 notifications aren't available; fall back to iOS 8-9 notifications.
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[application registerUserNotificationSettings:settings];
}
[application registerForRemoteNotifications];
return YES;
}
// [START receive_message]
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
// Print message ID.
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", userInfo);
}
- (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
// With swizzling disabled you must let Messaging know about the message, for Analytics
// [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
// Print message ID.
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", userInfo);
completionHandler(UIBackgroundFetchResultNewData);
}
// [END receive_message]
// [START ios_10_message_handling]
// Receive displayed notifications for iOS 10 devices.
// 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;
// With swizzling disabled you must let Messaging know about the message, for Analytics
// [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
// Print message ID.
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", userInfo);
// Change this to your preferred presentation option
completionHandler(UNNotificationPresentationOptionAlert);
NSLog(#"App is on foreground");
}
// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void(^)(void))completionHandler {
NSDictionary *userInfo = response.notification.request.content.userInfo;
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", userInfo);
completionHandler();
}
// [END ios_10_message_handling]
// [START refresh_token]
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
NSLog(#"FCM registration token: %#", fcmToken);
// Notify about received token.
NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:#"token"];
[[NSNotificationCenter defaultCenter] postNotificationName:
#"FCMToken" object:nil userInfo:dataDict];
NSLog(#"All is done");
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set [Messaging messaging].shouldEstablishDirectChannel to YES.
- (void)messaging:(FIRMessaging *)messaging didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage {
NSLog(#"Received data message: %#", remoteMessage.appData);
}
// [END ios_10_data_message]
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Unable to register for remote notifications: %#", error);
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// Get Device Tokens....
NSLog(#"APNs device token retrieved: %#", deviceToken);
// With swizzling disabled you must set the APNs device token here.
// [FIRMessaging messaging].APNSToken = deviceToken;
}
You need to uncomment this line:
[FIRMessaging messaging].delegate=self;
FCM provides the token via FIRMessagingDelegate's messaging:didReceiveRegistrationToken: method and you need to assign a delegate to FIRMessaging in order for that method to be called.
I am using FCM notifications and the notification will be triggered from a server.
When I am sending the notification from firebase console the following method is getting called and the notification is displayed in the device .
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
But the same method is not getting called when notification is sent from server.
Here is my code.
#import "AppDelegate.h"
#import "ViewController.h"
#import "TabBarViewController.h"
#import "Reachability.h"
#import GooglePlaces;
#import GooglePlacePicker;
#import GoogleMaps;
#import Firebase;
#import FirebaseMessaging;
#import UserNotifications;
#import <UserNotifications/UserNotifications.h>
#interface AppDelegate ()<UNUserNotificationCenterDelegate,FIRMessagingDelegate>
#end
#implementation AppDelegate
NSString *const kGCMMessageIDKey = #"gcm.message_id";
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// [START configure_firebase]
[FIRApp configure];
// [END configure_firebase]
// [START set_messaging_delegate]
[FIRMessaging messaging].delegate = self;
// [END set_messaging_delegate]
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(tokenRefreshCallback:) name:kFIRInstanceIDTokenRefreshNotification object:nil];
// 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.
// [START register_for_notifications]
if ([UNUserNotificationCenter class] != nil) {
// iOS 10 or later
// For iOS 10 display notification (sent via APNS)
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
completionHandler:^(BOOL granted, NSError * _Nullable error) {
// ...
}];
} else {
// iOS 10 notifications aren't available; fall back to iOS 8-9 notifications.
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[application registerUserNotificationSettings:settings];
}
[application registerForRemoteNotifications];
// [END register_for_notifications]
return YES;
}
- (void)tokenRefreshCallback:(NSNotification *)notification {
NSLog(#"instanceId_notification=>%#",[notification object]);
NSLog(#"FCM sire token =>%#",[[FIRInstanceID instanceID] token]);
// [FIRInstanceID instanceID] = [NSString stringWithFormat:#"%#",[notification object]];
[self connectToFirebase];
}
- (void)messaging:(nonnull FIRMessaging *)messaging
didRefreshRegistrationToken:(nonnull NSString *)fcmToken{
NSLog(#"didRefreshRegistrationToken :%#",fcmToken);
}
- (void)connectToFirebase {
//[FIRMessaging messaging].shouldEstablishDirectChannel = true;
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Unable to connect to FCM. %#", error);
} else {
NSLog(#" connected to FCM");
// you can send your token here with api or etc....
}
}];
}
//start notifications
// [START receive_message]
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// 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
// With swizzling disabled you must let Messaging know about the message, for Analytics
[[FIRMessaging messaging] appDidReceiveMessage:userInfo];
// Print message ID.
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message 1 ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#" 11 : %#", userInfo);
}
- (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
// With swizzling disabled you must let Messaging know about the message, for Analytics
//[[FIRMessaging messaging] appDidReceiveMessage:userInfo];
// Print message ID.
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message 2 ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#" 22 : %#", userInfo);
completionHandler(UIBackgroundFetchResultNewData);
}
// [END receive_message]
// [START ios_10_message_handling]
// Receive displayed notifications for iOS 10 devices.
// 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;
//new
//completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound);
// completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
// With swizzling disabled you must let Messaging know about the message, for Analytics
//[[FIRMessaging messaging] appDidReceiveMessage:userInfo];
// Print message ID.
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message 3 ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"33 :%#", userInfo[kGCMMessageIDKey][notification]);
// Change this to your preferred presentation option
if( [UIApplication sharedApplication].applicationState == UIApplicationStateInactive )
{
NSLog( #"INACTIVE" );
completionHandler(UNNotificationPresentationOptionAlert);
}
else if( [UIApplication sharedApplication].applicationState == UIApplicationStateBackground )
{
NSLog( #"BACKGROUND" );
completionHandler( UNNotificationPresentationOptionAlert );
}
else
{
NSLog( #"FOREGROUND" );
completionHandler( UNNotificationPresentationOptionAlert );
}
//completionHandler(UNNotificationPresentationOptionAlert);
//completionHandler(UNNotificationPresentationOptionBadge);
}
// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void(^)(void))completionHandler {
NSDictionary *userInfo = response.notification.request.content.userInfo;
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message 4 ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"44 : %#", userInfo);
//handle notification
completionHandler();
}
// [END ios_10_message_handling]
// [START refresh_token]
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
NSLog(#"FCM registration 5 token: %#", fcmToken);
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set [Messaging messaging].shouldEstablishDirectChannel to YES.
- (void)messaging:(FIRMessaging *)messaging didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage {
NSLog(#"Received data 6 message: %#", remoteMessage.appData);
//[self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:^(UIBackgroundFetchResult result) {
}
// [END ios_10_data_message]
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Unable to register for remote notifications 7 : %#", 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 device token can be paired to
// the FCM registration token.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"APNs device token retrieved 8 : %#", deviceToken);
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#"<>"]];
token = [token stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"content---%#", token);
NSLog(#"didRegisterForRemoteNotificationsWithDeviceToken");
NSLog(#"APNs device token retrieved: %#", deviceToken);
NSString *strDevicetoken = [[NSString alloc]initWithFormat:#"%#",[[[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]] stringByReplacingOccurrencesOfString:#" " withString:#""]];
NSLog(#"Device Token = %#",strDevicetoken);
[self.defaults setObject:strDevicetoken forKey:#"deviceToken"];
//.messaging().apnsToken = deviceToken
//new
// With swizzling disabled you must set the APNs device token here.
// [FIRMessaging messaging].APNSToken = deviceToken;
// // for development
// [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
//
// // for production
// // [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeProd];
[[FIRMessaging messaging] APNSToken];
NSLog(#"FIRMessaging device token retrieved 9 : %#", [FIRMessaging messaging].APNSToken);
NSLog(#"FIRMessaging device token retrieved 10 : %#", [FIRInstanceID instanceID].token);
}
- (void)applicationWillResignActive:(UIApplication *)application {
// 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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
- (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(#"disconnecfted from fcm");
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// 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.
}
- (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 connectToFirebase];
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
In info.plist FirebaseAppDelegateProxyEnabled is set to NO
Can some one please let me know How to fix the same.
I am trying to implement push notification using Firebase cloud messaging.I have followed firebase official tutorial from https://firebase.google.com/docs/cloud-messaging/ios/client
It works in simulator and i get the message which i sent from firebase console but it does not get InstanceID token(FCM token) when i try to build it in a device.
Here is my AppDelegate code
debugging environment : IOS 10.3
//---------------PUSH NOTIFICATION IMPLEMENTED HERE------------------
- (BOOL)application: (UIApplication*)application
didFinishLaunchingWithOptions: (NSDictionary*)launchOptions
{
// 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;
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
// For iOS 10 data message (sent via FCM)
[FIRMessaging messaging].remoteMessageDelegate = self;
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
// [END register_for_notifications]
}
//[[UIApplication sharedApplication] registerForRemoteNotifications];
// [START configure_firebase]
[FIRApp configure];
// [END configure_firebase]
// [START add_token_refresh_observer]
// Add observer for InstanceID token refresh callback.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(tokenRefreshNotification:)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
// [END add_token_refresh_observer]
return YES;
}
// [START receive_message]
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
// 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.
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", userInfo);
}
- (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.
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", 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 {
// Print message ID.
NSDictionary *userInfo = notification.request.content.userInfo;
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", userInfo);
}
// 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;
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", userInfo);
}
#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 {
[[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
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];
}
How can I show notification.please help
Thanks in advance
There is nothing to change.I set a message from firebase console for later delivery and it works perfectly.firebase console time and my iphone time mismatch that's why it did not send the message immediately.
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]];
}
}
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: