- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
[FIRMessaging messaging].remoteMessageDelegate = self;
[[UIApplication sharedApplication] registerForRemoteNotifications];
[FIRApp configure];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(tokenRefreshNotification:)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[FIRMessaging messaging] disconnect];
NSLog(#"Disconnected from FCM");
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[self connectToFcm];
}
- (void)applicationWillTerminate:(UIApplication *)application {
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// Print message ID.
NSLog(#"message 1");
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", userInfo);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// Print message ID.
NSLog(#"message 2");
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
NSLog(#"%#", userInfo);
completionHandler(UIBackgroundFetchResultNewData);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
NSLog(#"message 3");
NSDictionary *userInfo = notification.request.content.userInfo;
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
NSLog(#"full data : %#", userInfo);
completionHandler(UNNotificationPresentationOptionAlert);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)())completionHandler {
NSDictionary *userInfo = response.notification.request.content.userInfo;
NSLog(#"message 1");
if (userInfo[kGCMMessageIDKey]) {
NSLog(#"Message ID: %#", userInfo[kGCMMessageIDKey]);
}
// Print full message.
NSLog(#"%#", userInfo);
completionHandler();
}
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
// Print full message
NSLog(#"applicationReceivedRemoteMessage : %#", remoteMessage.appData);
}
- (void)tokenRefreshNotification:(NSNotification *)notification {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *refreshedToken = [[FIRInstanceID instanceID] token];
NSLog(#"InstanceID token: %#", refreshedToken);
if(!(refreshedToken== nil)){
[defaults setValue:refreshedToken forKey:#"FcmToken"];
}
[self connectToFcm];
}
- (void)connectToFcm {
if (![[FIRInstanceID instanceID] token]) {
return;
}
[[FIRMessaging messaging] disconnect];
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Unable to connect to FCM. %#", error);
} else {
NSLog(#"Connected to FCM.");
}
}];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Unable to register for remote notifications: %#", error);
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"APNs token retrieved: %#", deviceToken);
}
enter code here
When app is in the background mode, message not coming. When app is running foreground mode message shows in applicationReceivedRemoteMessage function. I need to run some code when message comes when background mode. Can anyone give me the solution for get the notifications works in background mode.
FIRMessaging connection won’t be allowed to live when in background it
is prudent to close the connection.
Please find here reference for the same: disconnect()
FirebaseMessaging Framework Reference
Simple Logic About Chat Applications: Socket Connection
Generally, Chat applications connects with other nodes (devices) using socket connection to transmit real-time information between nodes. Socket connections are disconnected, when apps goes into background.
FirebaseMessaging works on same logic and hence is won't work in background.
To handle message transmission in background mode, use power of PushNotification.
Also mark your code: You are disconnecting FIRMessaging when application goes into background. And you've done this, because the same is instructed in FIRMessaging guidelines.
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[FIRMessaging messaging] disconnect];
NSLog(#"Disconnected from FCM");
}
As an alternate solution of your problem: You may have analyzed Whatapp or Facebook Messagner app. They use push notification to alert user for messages, when app goes into background. You should do the same.
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.
Currently struggling with the following error showing up in logs:
<Error> [Firebase/Auth][I-AUT000015] The UIApplicationDelegate must handle remote notifcation for phone number authentication to work.
as well as this NSError object when calling verifyPhoneNumber:completion: :
#"NSLocalizedDescription" : #"If app delegate swizzling is disabled, remote notifications received by UIApplicationDelegate need to be forwarded to FIRAuth's canHandleNotificaton: method."
#"error_name" : #"ERROR_NOTIFICATION_NOT_FORWARDED"
Anyone know what this is about and how it can be solved?
I am using XCode 8.3.3, Firebase 4.0.0, I've switched OFF swizzling, and I already confirmed that I successfully register both for APNS (I see the token) and for FCM (I see this as well).
I used the sample code both in documentation and in the iOS cloud message github sample repo.
Before trying to integrate Firebase in the same project, I had Digits phone auth working flawlessly, and push notifications coming in both from AWS SNS and OneSignal.
Relevant code for Firebase-related parts:
AppDelegate
+ (void)initialize
{
FIROptions *firOptions = [[FIROptions alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"some-plist-name" ofType:#"plist"]];
[FIRApp configureWithOptions:firOptions];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[FIRMessaging messaging].delegate = self;
[FIRMessaging messaging].shouldEstablishDirectChannel = YES;
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
// do some other setup stuff here ...
return YES;
}
#pragma mark - FIRMessagingDelegate
- (void)messaging:(nonnull FIRMessaging *)messaging didRefreshRegistrationToken:(nonnull NSString *)fcmToken {
// I get an fcmToken here as expected and notify the the relevant controller(s)
}
- (void)messaging:(nonnull FIRMessaging *)messaging didReceiveMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage {
}
#pragma mark - UNUserNotificationCenterDelegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
NSDictionary *userInfo = notification.request.content.userInfo;
[[FIRAuth auth] canHandleNotification:userInfo];
completionHandler(UNNotificationPresentationOptionNone);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler {
completionHandler();
}
#pragma mark - Notifications
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
FIRMessagingAPNSTokenType tokenType = FIRMessagingAPNSTokenTypeProd;
#if DEBUG && !TESTFLIGHT
tokenType = FIRMessagingAPNSTokenTypeSandbox;
#endif
[[FIRMessaging messaging] setAPNSToken:deviceToken type:tokenType];
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
[[FIRAuth auth] canHandleNotification:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[[FIRAuth auth] canHandleNotification:userInfo];
}
- (void)application:(UIApplication *) application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)notification completionHandler:(void (^)())completionHandler {
completionHandler();
}
#end
Controller 1
...
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
[[UIApplication sharedApplication] registerForRemoteNotifications];
...
Controller 2 - after receiving APNS and FCM OK
...
[[FIRPhoneAuthProvider provider] verifyPhoneNumber:#"+11111111"
completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {
// Here is where I get that error.
}];
...
you have missed to add this method in your AppDelegate
func application(_ application: UIApplication,
didReceiveRemoteNotification notification: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if Auth.auth().canHandleNotification(notification) {
completionHandler(.noData)
return
}
// This notification is not auth related, developer should handle it.
handleNotification(notification)
}
I'm trying to be notified in background, I followed the documentation Firebase and Apple but I can´t solve my problem.
Problem: When I send a notification from the console Firebase I receive notification perfectly foreground, but sending the same notification from Firebase and my application is in background I do not receive any data, however if I open the application, the application shows me notification, but never in background. And the funny thing is that the next day I receive all notifications in the background with the closed application.
Device: iPhone 6 - v10.0.1
EDIT: My payload:
When I send a notification in Firebase, I receive this payload, I selected high priority in Firebase but I don´t receive any priority in the payload.
My code:
#define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#interface AppDelegate ()
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self registerForRemoteNotifications];
[FIRApp configure];
[self connectToFcm];
return YES;
}
- (void)registerForRemoteNotifications {
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){
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
}];
NSLog(#"Version >= 10");
}
else {
NSLog(#"version < 10");
// Code for old versions
}
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
NSLog(#"MODO 1: User Info: %#",notification.request.content.userInfo);
completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}
//Called to let your app know which action was selected by the user for a given notification.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
NSLog(#"MODO 2: User Info: %#",response.notification.request.content.userInfo);
completionHandler();
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
}
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
NSLog(#"My token is: %#", deviceToken);
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
NSLog(#"Failed to get token, error: %#", error);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
for (NSString *key in userInfo) {
NSLog(#"key value: %#", key);
if ([key isEqualToString:#"notification"]) {
NSString *body = [[userInfo valueForKeyPath:key] objectForKey:#"body"];
NSLog(#"message content: %#", body);
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
notification.repeatInterval = NSDayCalendarUnit;
notification.alertBody = body;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
notification.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
}
NSLog(#"Message ID: %#", userInfo[#"gcm.message_id"]);
if( [UIApplication sharedApplication].applicationState == UIApplicationStateInactive )
{
NSLog( #"INACTIVE" );
completionHandler( UIBackgroundFetchResultNewData );
}
else if( [UIApplication sharedApplication].applicationState == UIApplicationStateBackground )
{
NSLog( #"BACKGROUND" );
completionHandler( UIBackgroundFetchResultNewData );
}
else
{
NSLog( #"FOREGROUND" );
completionHandler( UIBackgroundFetchResultNewData );
}
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(#"enter in background");
}
- (void)connectToFcm {
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Unable to connect to FCM. %#", error);
} else {
NSLog(#"Connected to FCM.");
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"registeredToFCM"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}];
}
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]];
}
}