evollu / react-native-fcm

react native module for firebase cloud messaging and local notification
MIT License
1.73k stars 681 forks source link

ios notification not received but sent from api successfully. #526

Closed niranjan-b-prajapati closed 6 years ago

niranjan-b-prajapati commented 7 years ago

Hi,

Following are the versions:

react: 16.0.0-alpha.6, react-native: 0.44.0, react-native-fcm: ^7.2.0,

I have tested on iphone 6 ios 10.3.2

Following is the code in appdelegate.m:

#import "RNFIRMessaging.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [FIRApp configure];
  [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];

  NSURL *jsCodeLocation;

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"high_furtados_appv2"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
  NSLog(@"willPresentNotification %@",notification);
  [RNFIRMessaging willPresentNotification:notification withCompletionHandler:completionHandler];
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
  NSLog(@"didReceiveNotificationResponse %@",response);
  [RNFIRMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
    NSLog(@"didReceiveRemoteNotification %@",userInfo);
    [RNFIRMessaging didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

//You can skip this method if you don't want to use local notification
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    [RNFIRMessaging didReceiveLocalNotification:notification];
}

Following is the code in react-native project:

FCM.requestPermissions();
FCM.subscribeToTopic('all');
FCM.getFCMToken().then(token => {
            console.log('getFCMToken :::: ', token);
            // store fcm token in your server
            if (token) {
                global.pushToken = token
            }
            console.log('getFCMToken global.pushToken ::: ', global.pushToken);
 });
this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => {
            console.log('notificationListener notif ::: ', notif);
            let notificationIos = typeof notif == 'string' ? JSON.parse(notif) : notif;
            let notificationIosBody = {};
            try {
                notificationIosBody = notificationIos.notification.body;
            } catch (e) {
                try {
                    notificationIosBody = notificationIos.aps.alert.body;
                } catch (e) {
                    console.log("Format Error!");
                }
            }

            // there are two parts of notif. notif.notification contains the notification payload, notif.data contains data payload
            if (notif.local_notification) {
                //this is a local notification
            }
            if (notif.opened_from_tray) {
                //app is open/resumed because user clicked banner
                console.log('notificationListener notif.opened_from_tray ::: ', notif);
                if (Platform.OS === 'ios') {
                    if (notificationIosBody) {
                        Alert.alert('Notification', notificationIosBody,
                            [
                                { text: 'OK', onPress: () => { } },
                            ]);
                    }
                }
            }

            if (Platform.OS === 'ios') {
                 if (notificationIosBody) {
                    Alert.alert('Notification', notificationIosBody,
                        [
                            { text: 'OK', onPress: () => { } },
                        ]);
                }
            }
            else if (Platform.OS === 'android') {
                if (notif.fcm.body) {
                    Alert.alert('Notification', notif.fcm.body,
                        [
                            { text: 'OK', onPress: () => { } },
                        ]);
                }
            }
        });
this.refreshTokenListener = FCM.on(FCMEvent.RefreshToken, (token) => {
            console.log('refreshTokenListener ::: ', token);
            // fcm token may not be available on first load, catch it here
            if (token) {
                global.pushToken = token
            }
            console.log('refreshTokenListener global.pushToken ::: ', global.pushToken);
        });

I have added all the packages as mentioned in readme file for nonpod configuration.

I am not getting any logs which are added in appdelegate.m file.

The notifications are not getting received in ios only when app is open and also when app is closed or in background.

I have also added following in info.plist:

<key>FirebaseAppDelegateProxyEnabled</key>
    <false/>
guns2410 commented 7 years ago

+1 Having same issue

luisfuertes commented 7 years ago

Here @evollu said that FirebaseAppDelegateProxyEnabled must be on YES, can you check it with YES value?

niranjan-b-prajapati commented 7 years ago

@luisfuertes Earlier the FirebaseAppDelegateProxyEnabled entry was not there in info.plist and what i read was by default if the entry is not there the value is YES. At that time also the notifications were not getting received. So i tried by setting it as No as someone suggested on stackoverflow. @evollu Can you please help me out with this weird issue.

evollu commented 7 years ago

It could be payload being invalid. Is notification callback getting called? FirebaseAppDelegateProxyEnabled needs to be YES to make FCM hook on iOS's notification events

niranjan-b-prajapati commented 7 years ago

@evollu Thanks for replying. We have actually created new project with RN 0.44 as we want to upgrade react-native from 0.34 to 0.44, the old react-native project is still working and the notifications works fine in the old source code on IOS. Its this new project which is having problems in ios, as android notifications are received properly. The backend code is same as the notifications getting triggered on api calls.

luisfuertes commented 7 years ago

Im having the same issue too.

With old build of my app with react-native-fcm 6.2.3 it works, i understand all firebase console config its ok.

But yesterday i update react-native-fcm to v7.5.1, did pod update add FirebaseAppDelegateProxyEnabled = NO on plist and now push donesnt work...

My versions now: "react-native-fcm": "7.5.1" "react-native": "0.43.3"

Maybe pod update install a firebase-sdk too recent for version 7.5.1 of react-native-fcm?

evollu commented 7 years ago

try reregister the device? could FCM token get changed? I'm using RN 0.44 as well and thing looks fine to be. Will test with latest firebase SDK later but it shouldn't matter

niranjan-b-prajapati commented 7 years ago

@evollu Ok Will try that thing also, But what i did to test was took the push token i received in ios app and went to firebase console and tried to test notification using token, but still the notification was not received but was send successfully from firebase console.

evollu commented 7 years ago

BTW, you can update to 9.1.0. It should be compatible with 0.44. Mind the breaking change of sound though

luisfuertes commented 7 years ago

And with 0.43.3?

evollu commented 7 years ago

yes

niranjan-b-prajapati commented 7 years ago

@evollu Ok will try and get back to you on same.

luisfuertes commented 7 years ago

Ok im trying with v9.1.0 and did pod update again.

FirebaseAppDelegateProxyEnabled must be setted to YES or NO?

evollu commented 7 years ago

keep it YES

luisfuertes commented 7 years ago

Not works for me, push fail on firebase console captura de pantalla 2017-08-29 a las 12 37 49

luisfuertes commented 7 years ago

AppDelegate code:

#import "AppDelegate.h"
#import "RNFIRMessaging.h"

#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

@implementation AppDelegate

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

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"myapp_app"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];

  //AÑADIDO FIREBASE MESSAGING
  [FIRApp configure];
  [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
  //FIN FIREBASE MESSAGING

  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

// AÑADIDO FCM
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
     [RNFIRMessaging willPresentNotification:notification withCompletionHandler:completionHandler];
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
  [RNFIRMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
}

 //You can skip this method if you don't want to use local notification
 -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
  [RNFIRMessaging didReceiveLocalNotification:notification];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
  [RNFIRMessaging didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// FIN FCM

@end

plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>es</string>
    <key>CFBundleDisplayName</key>
    <string>MyApp</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0.9</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>com.mycompany.myapp</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>com.mycompany.myapp</string>
            </array>
        </dict>
    </array>
    <key>CFBundleVersion</key>
    <string>109</string>
    <key>FirebaseAppDelegateProxyEnabled</key>
    <true/>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>whatsapp</string>
    </array>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    <key>NSCameraUsageDescription</key>
    <string>¿Da permiso para acceder a la cámara?</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string></string>
    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>¿Da permiso para almacenar el vídeo en el carrete?</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>¿Da permiso para acceder al carrete?</string>
    <key>UIAppFonts</key>
    <array>
        <string>Entypo.ttf</string>
        <string>EvilIcons.ttf</string>
        <string>FontAwesome.ttf</string>
        <string>Foundation.ttf</string>
        <string>Ionicons.ttf</string>
        <string>MaterialCommunityIcons.ttf</string>
        <string>MaterialIcons.ttf</string>
        <string>Octicons.ttf</string>
        <string>SimpleLineIcons.ttf</string>
        <string>Zocial.ttf</string>
    </array>
    <key>UIBackgroundModes</key>
    <array>
        <string>remote-notification</string>
    </array>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <true/>
</dict>
</plist>

Log on init app:

2017-08-29 12:32:51.461186+0200 myapp_app[509:128684] [Firebase/Analytics][I-ACS023007] Firebase Analytics v.40003000 started
2017-08-29 12:32:51.462 myapp_app[509] <Notice> [Firebase/Analytics][I-ACS023007] Firebase Analytics v.40003000 started
2017-08-29 12:32:51.463451+0200 myapp_app[509:128684] [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see http://goo.gl/RfcP7r)
2017-08-29 12:32:51.464 myapp_app[509] <Notice> [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see http://goo.gl/RfcP7r)
2017-08-29 12:32:51.547880+0200 myapp_app[509:128695] [Firebase/Messaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. Add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2017-08-29 12:32:51.551 myapp_app[509] <Notice> [Firebase/Messaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. Add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
evollu commented 7 years ago

I think fails means firebase failed to push, rather than the device failed to handle. try uninstall the app and reinstall?

luisfuertes commented 7 years ago

Ye but yesterday all works, dont know whyit fail now, i will try with old build of my app with v6.2.3. Same firebase console config. I think it will work

luisfuertes commented 7 years ago

Yes, it works with old build, same firebase console config :( captura de pantalla 2017-08-29 a las 12 48 28

luisfuertes commented 7 years ago

Ok now im trying on iPad.

In firebase console push set as sent, but dont received it on iPad captura de pantalla 2017-08-29 a las 12 55 41

I add breakpoints in xcode in all fcm functions with app open, and no function is called when i send a push from firebase console (and marked as success)

evollu commented 7 years ago

let me verify on my device

luisfuertes commented 7 years ago

I delete ios Pods folder and Podfile, reinstall pods and now all notif fail on firebase console , but project compile and device give FCM token

evollu commented 7 years ago

so it has to do with FCM SDK?

luisfuertes commented 7 years ago

who knows

luisfuertes commented 7 years ago

I delete all pods config, generate new app certificates and install react-native-fcm@9.1.0 and now all works fine...

Old build only works with old certificate, and new app with new certificate, the bundle id is the same and dont know why it happens

Thanks for support @evollu

evollu commented 7 years ago

certificate you mean the json object download from firebase console right?

evollu commented 7 years ago

@niranjan-b-prajapati let me know if @luisfuertes 's finding works for you

luisfuertes commented 7 years ago

Not, certificate the .p12 file, ios push certificate on firebase console project config. Dont know why the old certificate doesnt works with news builds.

niranjan-b-prajapati commented 6 years ago

@evollu sorry yesterday couldn't work on it as there was no electricity i will try it now, @luisfuertes New certificates means ? only apns ceritifcate or ?development, distribution certificate also from apple developer console ? Please enlighten me on the certificate thing till then will update reac-native-fcm to 9.1.0

luisfuertes commented 6 years ago

I update push dev and push prod p12 certificate, reinstall FirebaseMessaging pod and install react-native-fcm 9.1.0 with same config and all works ok now

niranjan-b-prajapati commented 6 years ago

the ios certificate on firebase console what we add .p12 file is exported from apns certificate installed on our system. So do we need to create new apns certificate and change that ? Also there is some keys section available in developer apple console should we use that ? And will changing new apns keys will affect the existing users who are using apps on old source code as they will be getting updates soon of new app build with new react-native source codes. @evollu @luisfuertes please put some light on this.

evollu commented 6 years ago

if it is .12 related, it shouldn't affect existing user. it is more of Firebase-APNS communication getting impacted

niranjan-b-prajapati commented 6 years ago

so if i create key instead of apns certificate and use in app it will not affect existing users ? Can you please explain " it is more of Firebase-APNS communication getting impacted" thing.

evollu commented 6 years ago

hmm..forget about it. Perhaps you need to test that.

niranjan-b-prajapati commented 6 years ago

Ok I am using firebase 4.0.4 sdk files do i need to update them to latest version available ?

jaysig commented 6 years ago

Any updates on this? I have followed all of the instructions, but I can never get a notification to appear. It does send from the API though.

olieidel commented 6 years ago

Here are my findings so far: iOS 10.3.3, RN 0.46.4

Update (see below):

My best guess would be that there is a server-side problem between the Firebase and with the APN servers.

This may be related: https://github.com/firebase/quickstart-ios/issues/273

olieidel commented 6 years ago

Quick Update: I implemented React Natives PushNotificationIOS for my app and it has the same problem! I am getting a token but not receiving any messages. Even weirder, my older version with firebase (in production) works - but not in development. I suspect it is some certificate-related issue and has nothing to do with this package.

natashache commented 6 years ago

I'm having the similar issue. I'm able to get device token from my app. Sending messages from both node.js backend and from firebase notifications console indicates that message has been sent successfully. But it doesn't show up on the mobile app. App capacities, etc have been configured exactly as in the readme of react-native-fcm.

And the strange part is that it was working yesterday. But not today. And I haven't changed anything in the app. So frustrated right now!

olieidel commented 6 years ago

@natashache this really does sound like a backend problem on the side of Apple. I just reverted to a commit in my project which worked yesterday and it doesn't work any more! I hope this is one of those problems which fix themselves over night..

natashache commented 6 years ago

@olieidel will let you know if it fixes itself. Though I'm getting messages from other apps with no problem. If someone has insight on this, please share.

olieidel commented 6 years ago

Relevant discussions: Apple Developer Forums thread:

Stackoverflow questions in the last 24hrs:

vrgimael commented 6 years ago

I had the same problem but this morning I received all my delayed test notifications together (they had the correct timestamp though) and now notifications seem to be working fine again. Anyone else?

natashache commented 6 years ago

Just tried again. Still not receiving messages :(

olieidel commented 6 years ago

@natashache it's working for me again, too. I filed a bug report with Apple and 2 hours later it was resolved (probably unrelated though, haha).

natashache commented 6 years ago

I have followed this guide to debug https://firebase.googleblog.com/2017/01/debugging-firebase-cloud-messaging-on.html. I made a curl call directly through APNs and the notification showed up on my phone with no problem.

But when I made a curl call through FCM, I was not able to get the message on phone, though the response from firebase said the message had been sent and I didn't get any error messages. Here's the response: {"multicast_id":5824867483593933267,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1504535298633785%0007825f0007825f"}]}

I again tried sending messages via firebase notification console. Still no dice. But the console says message has been sent successfully.

evollu commented 6 years ago

@natashache can you verify that p12 file is correct? also can you show your payload? invalid payload will result notification not showing

natashache commented 6 years ago

@evollu I'm using APNs authentication key, not p12 file.

The curl command:

curl --header "Content-Type: application/json" \
--header "Authorization: key=AU...the rest of your server key...s38txvmxME-W1N4" \
https://fcm.googleapis.com/fcm/send \
-d '{"notification": {"body": "Hello from curl via FCM!", "sound": "default"},
"priority": "high",
"to": "gJHcrfzW2Y:APA91...the rest of your FCM token...-JgS70Jm"}'

As you can see the payload is nothing special.

Also tried sending with notification console.

It was working two days ago and then stopped working. Haven't changed a thing.

evollu commented 6 years ago

try include a title? .p12 file is used by FCM so try upload that file in firebase console again?

aditya27dev commented 6 years ago

@niranjan-b-prajapati I am getting Failed to grant permission with request permission. Did you manage to do that? If yes, please let me know how.

Thanks