evollu / react-native-fcm

react native module for firebase cloud messaging and local notification
MIT License
1.73k stars 682 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/>
niranjan-b-prajapati commented 7 years ago

@MrPeproni i never got that kind of issue. Sorry @evollu couldn't reply on the issue as i was assigned some other issues to fix first. I am yet to implement and check whatever solutions given above will try setup in new blank project and check with fresh certificate and keys. As still the notifications are not getting received on react-upgraded build but working fluently on old setup. Thanks @olieidel @natashache @luisfuertes @jaysig @vrgimael for reporting this issue atleast came to know many people are facing the issue on latest source while old ones are working perfectly.

niranjan-b-prajapati commented 7 years ago

@evollu I have created new react-native project with same version as above 0.44.0 and set up fcm only for ios using apns key instead of certificate and tested using the fcm console for single device by using the fcm token received in app and logged the notification json data in notificationListener function. I have successfully received the notification json data in the newly created project.

But when i tried sending notification to single device using fcm token received in the above mentioned react-native upgraded project where i am getting issue of notification not getting received, i have not received any notification.

Is this happening due to apns certificate? Main thing i am wondering is why it is happening as the same fcm project with same apns certificate and all settings is working fine in my old react-native project on version 0.34 and same thing doesn't work on 0.44 where whole code is updated.

Request you to assist me as we have created separate bundle id for testing environment and production, and very much afraid to change apns certificate, as if i change apns certificate in testing environment then will have to change same in production environment, how can i solve the issue without changing the apns certificate.

evollu commented 7 years ago

did you update firebase SDK?

niranjan-b-prajapati commented 7 years ago

used same 4.1.0 in both latest test project where notification working and the upgraded project in which i am facing issue. as nanopb.framework file is there in 4.1.0, where as my old source code of RN version 0.34 has SDK 4.0.4 where notification works fine.

evollu commented 7 years ago

can you ask Firebase team if they know anything about it? try delete the app and install again and see if new fcm token work. If it works, we will think about some work around

niranjan-b-prajapati commented 7 years ago

Ok can you point me in right direction how can i contact them ?

evollu commented 7 years ago

https://firebase.google.com/support/

niranjan-b-prajapati commented 7 years ago

@evollu Following is the response from the firebase:

Firebase does not officially support react-native yet. Based on the cause of the issue, it seems that you experienced it after upgrading your react-native to a newer version. I suggest that you ask the issue in developer communities like StackOverflow or in the link you've provided as it's currently outside of our scope of support. However, if you could replicate the issue using the native languages (Objective-C/Swift, Android/Java), please let me know and I'd be happy to assist here.

very much worried what to do now in these scenario.

Sorry didn't saw your following comment in haste:

try delete the app and install again and see if new fcm token work. If it works, we will think about some work around

Trying it right away and let you know if that works, hope it works fingers crossed.

niranjan-b-prajapati commented 7 years ago

I tried deleting app and running again and checked using fcm console single device using fcm token received in app, Also i tried by removing the fcm sdk and adding it again to check if this might solve issue, but all in vain. notification send from console but not receive in app. Also one thing i noticed is that i had kept debugger point in the following function

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

The function is not getting called when the notification is sent from fcm console. while in the temp testing project the function is getting called when notification is sent from fcm console using fcm token.

evollu commented 7 years ago

@niranjan-b-prajapati your finding means the notification has never made to your phone so it is not caused by react native or this lib. Deleting the app and reinstalling will give the device a new FCM token. are you using the new token? if so, it means your token from SDK 4.1.0 doesn't work with the console. What I would do is downgrade to SDK 4.0.4 and check if it will work again.

paomosca commented 6 years ago

hey @evollu i falling in the same exact situation, i tried the curl call directly to apns and it works, then i tried the curl by firebase and the results is

{"multicast_id":5351961100343884262,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1506010515803885%bd25912cbd25912c"}]}%

but no message on device:

the version of firebase pod i'm using is:

Using Firebase (4.2.0) Using FirebaseAnalytics (4.0.3) Using FirebaseCore (4.0.7) Using FirebaseInstanceID (2.0.3) Using FirebaseMessaging (2.0.3) Using GoogleToolboxForMac (2.1.1) Using Protobuf (3.4.0) Using nanopb (0.3.8)

any hints? how to downgrade to 4.0.4?

natashache commented 6 years ago

@paomosca do you have

<key>FirebaseAppDelegateProxyEnabled</key>
<true/>

in your info.plist? I had the same problem and that was what solved it for me.

paomosca commented 6 years ago

@natashache i tried with true and false values, but nothing changed. i even tried to delete and create p12 certs and p8 keys too, but nothing.

(RN version 0.47.2 & react-native-fcm 9.1.0, but also i have the same problem with 9.3.0)

evollu commented 6 years ago

@paomosca what's your payload to firebase?

paomosca commented 6 years ago

curl --header "Content-Type: application/json" \ --header "Authorization: key=SERVER_KEY" \ https://fcm.googleapis.com/fcm/send \ -d '{"notification": {"body": "Hello from curl via FCM", "title":"test", "sound": "default"}, "priority": "high", "to": "FCM_DEVICE_TOKEN"}'

very basic

evollu commented 6 years ago

@paomosca payload looks right. try uninstall the app and get a new FCM token? is remoteNotification method in AppDelegate.m getting called at all?

paomosca commented 6 years ago

i already tried several times. the remotenotification method never fires. i just tried to use 4.0.4 version of the Firebase SDK and is not working either.

I thought was a bug of firebase system, maybe related to ios 11 update, but if you can make it work, this is not possible.

evollu commented 6 years ago

could be...can you try ios 10 then? I haven't tried 11

paomosca commented 6 years ago

ok i've some news. today i created a clean project with new bundle id, new certs and new app on Firebase, using: "react-native": "0.48.3", "react-native-fcm": "^9.3.0"

i can handle correctly push notifications.

the project i was testing yesterday was using also the firebase sdk module "firebase": "^4.3.1" to access firebase database & auth capabilities

it is possible this is generating some conflicts?

evollu commented 6 years ago

@paomosca so you say you used same firebase SDK, but new project just works? there shouldn't be any conflicts between react-native-fcm and react-native not sure about react-native vs firebase SDK but not likely

I guess something is messed up with the old bundle id?

paomosca commented 6 years ago

@evollu i'm getting crazy, because i linked "firebase": "^4.4.0" on the working project, and it still working. then i changed all the libs on the "not working" project, and i changed the bundle id to be the same of the working one.... but... still not working....

is a really weird situation... i'm thinking to move my code from not working to working project... but it will require some time... i'll let you know if i can make it works.

paomosca commented 6 years ago

@evollu ok i found an example to reproduce the failure 100%.

use "react-native": "0.48.3" (but also with 0.47.*) "react-native-fcm": "^9.3.0"

run your example: simple-fcm-client

it will work with all the examples now npm i -S firebase it will install "firebase": "^4.4.0"

clean and reinstall.

the project won't send the push anymore (in log you can see the sending from client correctly but not the received).

tested on iphone 5s ios 10.2

i hope it will help to investigate where is the problem, now i'm pretty sure there is some conflict between react-native-fcm and firebase SDK

evollu commented 6 years ago

wait. why are you installing javascript sdk? you should be using iOS and Android SDK

paomosca commented 6 years ago

i had a working app using firebase (js sdk) for database & react-native-fcm for push, it was working correctly until the last month, when it stopped without any change. i'm using firebase js sdk because is way simpler to use than integrating native SDKs on both platform.

evollu commented 6 years ago

@paomosca This repo doesn't call any firebase JS library method and isn't designed to work with JS library.

I looked at the firebase js sdk implementation and it is hooking on registration and message callback as well. so there might be a conflict both sdk trying to handle it. possible 2 fcm tokens are issued? did you call any js sdk messaging method?

anyway, if you want to send simple notification which firebase SDK provides, you can just use that SDK. If you want complex feature, perhaps you need to find a way to have this 2 sdk work together. perhaps ask https://github.com/firebase/firebase-js-sdk what did they do in v4.4.0?

nielskrijger commented 6 years ago

Had the same issues as described above; receiving no notifications. Took me more than a day without getting anywhere.

Eventually downloaded the example project and it worked; with the same .p8 key file and same project ID on firebase.

After looking through the differences, as it turned out, in my main project the Podfile.lock was not included. When I copied the Podfile.lock from the example project into my main project it worked.

I think it has to do something with the FirebaseInstanceId peerdependency.

Just to analyze the issue I fixed the Pods to their respective versions in Podfile and removed the Podfile.lock again:

pod 'Mixpanel', '~> 3.2'
pod 'Firebase/Core', '4.0.0'

which generated the following Podfile.lock:

PODS:
  - Firebase/Core (4.0.0):
    - FirebaseAnalytics (= 4.0.0)
    - FirebaseCore (= 4.0.0)
  - Firebase/Messaging (4.0.0):
    - Firebase/Core
    - FirebaseMessaging (= 2.0.0)
  - FirebaseAnalytics (4.0.0):
    - FirebaseCore (~> 4.0)
    - FirebaseInstanceID (~> 2.0)
    - GoogleToolboxForMac/NSData+zlib (~> 2.1)
  - FirebaseCore (4.0.0):
    - GoogleToolboxForMac/NSData+zlib (~> 2.1)
  - FirebaseInstanceID (2.0.3)
  - FirebaseMessaging (2.0.0):
    - FirebaseAnalytics (~> 4.0)
    - FirebaseCore (~> 4.0)
    - FirebaseInstanceID (~> 2.0)
    - GoogleToolboxForMac/Logger (~> 2.1)
    - Protobuf (~> 3.1)
  - GoogleToolboxForMac/Defines (2.1.1)
  - GoogleToolboxForMac/Logger (2.1.1):
    - GoogleToolboxForMac/Defines (= 2.1.1)
  - GoogleToolboxForMac/NSData+zlib (2.1.1):
    - GoogleToolboxForMac/Defines (= 2.1.1)

Now notifications no longer worked!

Whereas the example projects shows:

PODS:
  - Firebase/Core (4.0.0):
    - FirebaseAnalytics (= 4.0.0)
    - FirebaseCore (= 4.0.0)
  - Firebase/Messaging (4.0.0):
    - Firebase/Core
    - FirebaseMessaging (= 2.0.0)
  - FirebaseAnalytics (4.0.0):
    - FirebaseCore (~> 4.0)
    - FirebaseInstanceID (~> 2.0)
    - GoogleToolboxForMac/NSData+zlib (~> 2.1)
  - FirebaseCore (4.0.0):
    - GoogleToolboxForMac/NSData+zlib (~> 2.1)
  - FirebaseInstanceID (2.0.0):
    - FirebaseCore (~> 4.0)
  - FirebaseMessaging (2.0.0):
    - FirebaseAnalytics (~> 4.0)
    - FirebaseCore (~> 4.0)
    - FirebaseInstanceID (~> 2.0)
    - GoogleToolboxForMac/Logger (~> 2.1)
    - Protobuf (~> 3.1)
  - GoogleToolboxForMac/Defines (2.1.1)
  - GoogleToolboxForMac/Logger (2.1.1):
    - GoogleToolboxForMac/Defines (= 2.1.1)
  - GoogleToolboxForMac/NSData+zlib (2.1.1):
    - GoogleToolboxForMac/Defines (= 2.1.1)
  - Mixpanel (3.2.1)
  - Protobuf (3.4.0)

The only difference I see are the following lines:

  - FirebaseInstanceID (2.0.0):
    - FirebaseCore (~> 4.0)

If that is included it works for me. FirebaseInstanceID 2.0.3 wouldn't work whatever I did.

evollu commented 6 years ago

there is a known FCM bug for FirebaseInstanceID 2.0.1-2.0.3. lock pod version to 2.0.0 for now let me know if this doesn't work for you

fredbt commented 6 years ago

Is this fixed now? We're having a similar issue here, which does not seem to be fixed by locking FirebaseInstanceID to 2.0.0: we get the token for IOS, etc, but never gets notifications that our server sends to FCM. After we go to the Firebase console and send one notification to this specific token, then all the other messages that we had sent before get somehow "flushed" in a single batch.

So, it seems like that sending one message from the firebase triggers the release of other messages.

LMK if I should open a new issue for this.

evollu commented 6 years ago

sounds like a question for firebase team.

ducpt2 commented 6 years ago

+1 same issue. I try using onesignal to push notification and it work. May be you right @evollu , can you update the news here, when the issue is end?

philjoseph commented 6 years ago

I am using react-native-fcm and the firebase JS SDK 3.9.0 and have a similar issue

It seems like there is a refresh token event I do not catch but I do have a listener:

const refreshTokenListener = FCM.on(FCMEvent.RefreshToken, (token) => {
    // fcm token may not be available on first load, catch it here
    registerFCMToken(token);
});

Any idea why my token is loosing its correctness and how I could catch the refresh event? Note that is was working perfectly few weeks ago

evollu commented 6 years ago

@philjoseph introduced a fix in v13.1.0 which will delay FCMEvent.RefreshToken event to be handled by JS. To be safe, you can store users fcm token locally and compare with getFCMToken() every time user launches the app

philjoseph commented 6 years ago

@evollu I've tried to upgrade to 13.1.0 and hit #790.

nsuryanarayanareddyn commented 6 years ago

any solution for this issue ???

amberkatyal commented 5 years ago

Would like to add my few words if help to any. My issue was only the improper implementation. If you've separate environments configured in your project shifting from uat to production. Make sure the refreshToken delegate method is implemented :). Realized when reinstalled the app.

gotozainishaikh commented 4 years ago

@paomosca do you have

<key>FirebaseAppDelegateProxyEnabled</key>
<true/>

in your info.plist? I had the same problem and that was what solved it for me. thanks for your advice