React-native-fcm: Notifications not received when app is suspended iOS 11

Created on 27 Sep 2017  Â·  36Comments  Â·  Source: evollu/react-native-fcm

RN: 0.48.4
react-native-fcm: 9.5.0
iPhone 7+ iOS 11
@evollu

With the new iOS 11 update, push notifications are now received if the app is in the background, but they fail to arrive if the app is in suspended state. No logs are shown and no notification is shown.

When the app is open, push notifications are received as a callback (expected).

I've added content_available true to the payload, what else is needed to ensure the push is always delivered?

    admin.messaging()
    .sendToDevice(token, {
      notification: {
        title: 'title',
        body: 'body',
      }
    }, {
      contentAvailable: true,
      priority: 'high',
      timeToLive: 60 * 30,
      show_in_foreground: true
    })

Most helpful comment

just a reminder, FirebaseInstanceID >2.0.1 has known issue with iOS11, make sure you have pod 'FirebaseInstanceID', '2.0.0' in your pod file

All 36 comments

how do you trigger suspended?

The phone puts the phone into suspended state whenever it needs to.

I am unable to trigger suspended in xCode.

On 27 September 2017 at 14:42, Libin Lu notifications@github.com wrote:

how do you trigger suspended?

—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
https://github.com/evollu/react-native-fcm/issues/580#issuecomment-332524680,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AA26uRZvu0bAN3wDPZ_XctzODt-8Y3WNks5smlC-gaJpZM4Plogo
.

@evollu
The same problem.
I send this payload and it works fine when app is opened(In foreground) and using, but when I put app into background(with out drop it from processes) it stop working.
If lock the device screen with and without opened app - notification callback didn't work also.
Problem only with iOS devices, on Android all works fine.

{
  "to":"device id is here",
   "content_available": true,
   "data": {
       "test": true
   }
}

React-native version 0.47.2
Module version 9.7.2
iOS version: 11.0.2

@Vetalyo did you try setting priority to high?

I managed to get it work more reliably (although still not 100%), it might be because of this change:

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
  [RNFirebaseMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
  completionHandler(); // <--------- ADD THIS
}

@gurmukhp, could you please explain, what do you mean by this code? Because I can't understand.
My code looks like:

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

I also try to send payload with priority high, nothing changed.

Try adding completionHandler(); before the last closing bracket.

Yeap, my bad, I didn't see that you edit your previous post. I've add this row but now payload didn't work at all, even when app opened.

I've found that if the app is open, the notification doesn't display, instead it comes through as a callback in the code.

I also tried this, not sure if it worked:

            this.firebase.messaging().onMessage((message) => {
              console.log('message received', message);
              message.finish();
            });

If the above doesn't work for you, then I'm not sure what it could be :/

It's works from time to time. Looks like that's problem with my app.
I think all should be fine when I find out what the reason and fix that.
Thank you very much for help, I very appreciate that.

completionHandler() is optional because the library should handle this automatically. let me know when you get updates

just a reminder, FirebaseInstanceID >2.0.1 has known issue with iOS11, make sure you have pod 'FirebaseInstanceID', '2.0.0' in your pod file

@evollu do you have more info about the issues with iOS 11?

@evollu Thanks for helping!
Yes, I have this line in my pod file pod 'FirebaseInstanceID', '2.0.0', I even already try version 2.0.4 but looks like it works in same manner. It works well while it's in foreground but enough move it to the back or lock device screen and it stop working or sometimes it's works in background and even when screen was locked but not a long time.
I can not understand the sequence, why it's like that.
From time to time it's works, but almost all the time it's don't.
That's make me a headache.

@evollu, can you provide me please?
To make onNotificationCallback work I need to import PushController like in example or I can include it in main file of my project?
Because now I use it like a function in my main file of app(App.js) and it's work fine on android.
So can it be a reason why it's not work on iOS?

@Vetalyo you can have the JS code anywhere as long as they are excited on launch.
To rule out SDK issue can you try iOS native example by firebase team?

@evollu, thank you. I try firebase native example, it works as expected.
Now I found that in my project, onNotification listener works well too, it fired when notification arrives. I try to receive current position, using navigator.geolocation.getCurrentPosition, and it stucks on them, sometimes it works, sometimes it doesn't, and it receive coordinates only after launch app.

But this another problem, plugin works well. Thank you for helping!

cool

@evollu , all test on native firebase example I try with connected phone to mac, and in this case all works fine, but today I found that, it does not work without cable. If app comes to background, even if screen is active now, on notification handler does not fire. I try this in you plugin, and in firebase native example. Can you help me please ?

My notification payload:

{
  "to":"device_id",
   "content_available": true,
    "priority": "high",
   "data": {
       "param": true
   }
}

so you say you have the problem with firebase native example as well? How do you know callback is fired when you try native example without cable?

I send request to my DB(change device status)

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("application:didReceiveRemoteNotification:fetchCompletionHandler: called, with notification:")

        var request = URLRequest(url: URL(string: "http://myserver/alala")!)
        request.httpMethod = "POST"
        let postString = "id=idHere&auth_key=authKeyHere"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(String(describing: responseString))")
        }
        task.resume()

        print("\(userInfo.jsonString ?? "{}")")
        completionHandler(.newData)
    }

with cable all works fine, otherwise it doesn't.

@evollu, I created issue in _firebase-ios-sdk_, check this out please
https://github.com/firebase/firebase-ios-sdk/issues/368

cool, let keep tracking it

Hey @evollu, could you please give me advise:
In this firebase/firebase-ios-sdk#368 thread I find out that didReceiveRemoteNotification callback works(without connected cable to device) but I cannot send post request. I've check that by increase app badge number on each silent push.
Maybe you know how to handle this situation?
Thank you.

@Vetalyo did you add Background fetch in iOS Capabilities?

Yes, of course.

from your issue there, I don't see you trying sending a post in local notification callback. does that work?

I try to send simple post request to my server by fetch and it's doesn't work.

FCM.on(FCMEvent.Notification, async (notif) => {
    //Here request code
});

well I'm confused.

  1. does fetch work with local notification?
  2. if you just fetch from google.com does that work?

I didn't test it with local notification.
When I received silent push notification I'm trying to get back to server some data by post request.

can you test it with local notification?
can you try posting something else to make sure it can do fetching in background?

@evollu
Okay, I'll test work of local notification.
Yeap, I have tried send fetch with GET request to server and it works but in very strange manere. It works from time to time, I can't understand from what it depends.
Thank you for reply!

To check local notifications I add lines which simple increase badge number. And it works perfect all the time.

Next I leave local notifications code and adding to them post request to my server with some data.
I think there is something like notification count limitation. Because sometimes I sending 5-15 notifications at short time it's stop changing badge at all, so - no response on silent push, until didn't open the app. And 50% times it works on 1-2 notifications.
Can't find out from what it depends.
I'm confused :disappointed:.
Any ideas?

ok. move completionHandler(.newData) inside your request callback.
completionHandler(.newData) will kill the app because you are telling OS you are done

But now I make my request in JavaScript

fetch(`http://server}`, {
             method: 'POST',
             headers: {
                 'Content-Type': 'application/json'
             },
             body: JSON.stringify({
                'id': id
                'auth_key': accessToken,
            })
         })
            .then((response) => {
              console.log(response);
              return response.json();
            })
            .then((resp) => {
              console.log(resp);
              FCM.setBadgeNumber(++counter);
            }).catch((error) => {
              console.log(error);
            });

I was using swift just to find out that silent push notification works as expected.

return the promise in the function.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nailikhaled picture nailikhaled  Â·  5Comments

Przemocny picture Przemocny  Â·  3Comments

sf577 picture sf577  Â·  3Comments

Keksike picture Keksike  Â·  5Comments

404sand808s picture 404sand808s  Â·  5Comments