flutterfire icon indicating copy to clipboard operation
flutterfire copied to clipboard

[firebase_messaging] iOS is not receiving apns payload and not showing notification when it is in background or killed

Open FernandoUFS opened this issue 6 years ago • 54 comments

Describe the bug A couple days ago I notice that my application stopped showing notifications from firebase just on iOS. I send a POST request to https://fcm.googleapis.com/fcm/send containing the payload, when the app is on background nothing happens, when I open the app the method onMessage is executed with few fields shown below.

The notification was working from about 2 months since first implementation, it was shown when the app was in background, my payload was not changed but it stopped working.

Expected Behaviour Show notification when app is in background or killed (as before)

My request: image

My alternative request with same result:

{
    "notification": {
        "title": "Title test",
        "body": "Body message"
    }
    "condition": "'match_1474' in topics"
}

My code for debug:

...
_firebaseMessaging.configure(
      onBackgroundMessage: myBackgroundMessageHandler, //static method printing message (not get called)
      onMessage: (Map<String, dynamic> message) async {
        Log.d("onMessage: ${jsonEncode(message)}");
      }
      onResume: (Map<String, dynamic> message) async {
        Log.d("onResume: ${jsonEncode(message)}");
      },
      onLaunch: (Map<String, dynamic> message) async {
        Log.d("onLaunch: ${jsonEncode(message)}");
      }
);
...

The console: This message is print only when I receive the notification with app open or when I open the app after receive with app closed.

flutter: onMessage: {"collapse_key":"4cH4++Z1SUoDiUf9+l9DKFX/sc=","from":"50068760310"}

Additional context I use AdminSDK for PHP for real use and the payload includes android specific data, but I tested on Postman to make sure the problem is not there.

The problem is occurring on production with all users I have checked (TestFlight Beta). On Android it is working as expected.

If I send just data the app continues receiving only when the app is on foreground. Example

{
    "data": {
        "title": "Title test",
        "body": "Body message"
    },
    "condition": "'match_1474' in topics"
}

The expected behaviour here is to receive the message in background executing immediately onMessage when it's not killed, but this happens only when app opens.

flutter doctor -v

[✓] Flutter (Channel stable, v1.17.4, on Mac OS X 10.15.3 19D76, locale pt-BR)
    • Flutter version 1.17.4 at /Users/fernando/Apps/flutter
    • Framework revision 1ad9baa8b9 (10 days ago), 2020-06-17 14:41:16 -0700
    • Engine revision ee76268252
    • Dart version 2.8.4
 
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at /Users/fernando/Library/Android/sdk
    • Platform android-29, build-tools 29.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.5)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.5, Build version 11E608c
    • CocoaPods version 1.8.4

[✓] Android Studio (version 4.0)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 46.0.2
    • Dart plugin version 193.7361
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)

[✓] VS Code (version 1.45.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.10.2

[✓] Connected device (1 available)
    • iPhone ... • ios • iOS 13.5.1

• No issues found!

pubspeck.yml dependencies

dependencies:
  flutter:
    sdk: flutter
  json_annotation: ^3.0.1
  jaguar_orm: ^2.2.7
  jaguar_query_sqflite: ^2.2.11
  device_info: ^0.4.2+4
  rxdart: ^0.22.2
  bloc_pattern: ^2.3.2
  dio: ^3.0.1
  intl: ^0.16.0
  sprintf: ^4.0.2
  firebase_messaging: ^6.0.16
  flutter_local_notifications: 1.4.3
  shared_preferences: ^0.5.6+1
  package_info: ^0.4.1
  mask_text_input_formatter: ^1.0.6
  admob_flutter: ^0.3.4
  archive: ^2.0.11
  appsflyer_sdk: ^5.2.0+1
  barcode_scan: ^1.0.0
  cached_network_image: ^2.0.0
  charts_flutter: ^0.8.1
  configurable_expansion_tile: ^1.0.0
  country_pickers: ^1.3.0
  cupertino_icons: ^0.1.3
  data_tables: ^1.0.3
  date_range_picker: ^1.0.5
  flare_flutter: ^1.0.2
  fl_chart: ^0.9.4
  flutter_cupertino_localizations: ^1.0.1
  flutter_slidable: ^0.5.3
  font_awesome_flutter: ^8.5.0
  image_picker: ^0.6.3+4
  path_provider: ^1.6.8
  provider: ^2.0.0
  pretty_qr_code: ^1.0.1
  share: ^0.6.3+6
  sqflite: ^1.2.0
  url_launcher: ^5.2.7
  webview_flutter: ^0.3.15+1
  google_sign_in: ^4.5.1
  flutter_svg: ^0.17.3+1
  flutter_localizations:
    sdk: flutter

FernandoUFS avatar Jun 27 '20 23:06 FernandoUFS

same issues :(. Please help!

vuvantoan95 avatar Jun 30 '20 02:06 vuvantoan95

you can set content_available and priority option In my case it solve the background and killed problem

whatamelon avatar Jul 01 '20 01:07 whatamelon

I`m facing the same problem right now, I tried the same request and the problem persists.

edjostenes avatar Jul 01 '20 15:07 edjostenes

you can set content_available and priority option In my case it solve the background and killed problem

@whatamelon From apple, the content-available option is for:

content-available : The background notification flag. To perform a silent background update, specify the value 1 and don't include the alert, badge, or sound keys in your payload. See Pushing Background Updates to Your App.

I don't want a silent notification in background, I want a normal notification to show to the user. I need include "alert". Anyway I tested content-available, it doesn't work :(

FernandoUFS avatar Jul 01 '20 18:07 FernandoUFS

I had the same issue. Pushes once worked but then randomly stopped working and I couldn't figure out why.

Here is a decent blog post on how to debug FCM for iOS: https://firebase.googleblog.com/2017/01/debugging-firebase-cloud-messaging-on.html

After following along I realized that my app was successfully getting the device token in didRegisterForRemoteNotificationsWithDeviceToken and was able to send pushes to my device via the NWPusher App which to me meant that FCM was simply failing to send to my APNS token.

I wish there was a way to be able to verify that your APNS token was in sync with your FCM token, but I assumed this could be the problem anyway.

I found at that at some point I disabled Swizzling by adding this to my plist:

<key>FirebaseAppDelegateProxyEnabled</key>
<false/>

*Some people mentioned changing this bool to a string NO would solve it, which simply just disables the flag re-enabling swizzling which turns back on the default APNS token set + analytics which could solve your issue too

I did this because I needed to grab the deviceToken for another purpose (use with Mixpanel). So in my AppDelegate.swift I override the didRegisterForRemoteNotificationsWithDeviceToken like so:

This is outlined in the references here:

  import FirebaseMessaging
  ...

  override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Mixpanel.mainInstance().people.addPushDeviceToken(deviceToken) //For Mixpanel purposes, not needed if not using
    Messaging.messaging().apnsToken = deviceToken //*THIS WAS MISSING*
    super.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) //Not sure if calling super is required, but did anyway
  }

I realized that if you disable swizzling you must set the APNS token manually or FCM will never know the device token meaning remote or background notifications will never come to the app.

So simply adding this line into the didRegisterForRemoteNotificationsWithDeviceToken callback fixed my issue:

Messaging.messaging().apnsToken = deviceToken

Side note:

If you disable swizzling, the FCM analytics won't automatically work (for deliveries and opens) so you'll have to add this code in to ensure FCM knows about it.

This is outlined in the references here:

  override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Swift.Void) {
    Messaging.messaging().appDidReceiveMessage(userInfo)
    ///Not sure if calling super is required here
    super.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
  }

robrichardson13 avatar Jul 09 '20 19:07 robrichardson13

@robrichardson13 Thanks for your solution, I did not realize that by disabling method swizzling I had to implement or call the functions that Firebase Message was handling in the background. In addition to the above, I would also emphasize that people call application.registerForRemoteNotifications() in the didFinishLaunchingWithOptions method as follows:

override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
    }
    GeneratedPluginRegistrant.register(with: self)
    application.registerForRemoteNotifications()  //* I Forgot This Line *
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}

kmdinake avatar Jul 13 '20 00:07 kmdinake

Hi @robrichardson13 thank's for your reply.

First, I didn't have <key>FirebaseAppDelegateProxyEnabled</key> on my Info.plist. Then I override the didRegisterForRemoteNotificationsWithDeviceToken on my AppDelegate.swift to get my device token and test at Pusher. Sending a push from Pusher worked. My app received and showed the notification in background.

So I added the <key>FirebaseAppDelegateProxyEnabled</key> to my Info.plist (tried the bool value false, and string value NO). This is my didRegisterForRemoteNotificationsWithDeviceToken function

override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
        print("==== didRegisterForRemoteNotificationsWithDeviceToken ====")
        print(deviceTokenString)
        Messaging.messaging().apnsToken = deviceToken
}

But after that, it happened exactly like before. The FCM can't deliver the notifications when the app is in background, only when it is in foreground.

Also I tested sending from FCM directly to my device token (not using topics), I get the same result.

I conclude that if the firebase can deliver notifications when app is in foreground, then it has the apn token registered successfully on its backend. @robrichardson13 Am I right about this conclusion?

I didn't solve my problem yet. I know that APN is working because I tested on Pusher, but when it is sent from FCM it's not working. I am not sure if it's related to firebase_messaging plugin. It seems like a problem between FCM and APN.

FernandoUFS avatar Jul 13 '20 23:07 FernandoUFS

Hi everyone.

Works in all situations on android but On launch and on resume do not trigger when app is in background or terminated. @robrichardson13 I tired your solution but it hasn't changed.

Flutter doctor version

ertugrul@ertugruls-Mac ~ % flutter doctor -v
[✓] Flutter (Channel stable, v1.12.13+hotfix.8, on Mac OS X 10.15 19A602, locale
en-TR)
• Flutter version 1.12.13+hotfix.8 at /Users/ertugrul/flutter
• Framework revision 0b8abb4724 (5 months ago), 2020-02-11 11:44:36 -0800
• Engine revision e1e6ced81d
• Dart version 2.7.0

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
• Android SDK at /Users/ertugrul/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling
support)
• Platform android-28, build-tools 29.0.3
• Java binary at: /Applications/Android
Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build
1.8.0_212-release-1586-b4-5784211)
✗ Android license status unknown.
Try re-installing or updating your Android SDK Manager.
See https://developer.android.com/studio/#downloads or visit
https://flutter.dev/setup/#android-setup for detailed instructions.

App Delegate.swift

import UIKit
import Flutter
import FirebaseMessaging

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("==== didRegisterForRemoteNotificationsWithDeviceToken ====")
print(deviceTokenString)
Messaging.messaging().apnsToken = deviceToken
}
}

Fcm code

_fcm.configure(onMessage: (Map<String, dynamic> message) async {
print("onMessage tetkilendi: $message");
showNotification(message);
},
onBackgroundMessage: Platform.isIOS?null:myBackgroundMessageHandler,
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch tetiklendi: $message");
showNotification(message);
},
onResume: (Map<String, dynamic> message) async {
print("onResume tetiklendi: $message");
showNotification(message);
},
);

Also Info.plist added

<key>FirebaseAppDelegateProxyEnabled</key> <string>NO</string>

Firebase messagin version is 6.0.16. Is there an error in the code I wrote or is it in the fcm package?

curlyeto avatar Jul 15 '20 09:07 curlyeto

Your android folder should be a Application.java file `package in.tvs.iex_driver;

import io.flutter.app.FlutterApplication; import io.flutter.plugin.common.PluginRegistry; import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService; import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin; import com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin;

public class Application extends FlutterApplication implements PluginRegistry.PluginRegistrantCallback {

@Override
public void onCreate() {
    super.onCreate();
    FlutterFirebaseMessagingService.setPluginRegistrant(this);
}

@Override
public void registerWith(PluginRegistry registry) {
    // I've only had to add this line to make it work
    FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
    FlutterLocalNotificationsPlugin.registerWith(registry.registrarFor("com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin"));
}

} `

saravananmnm avatar Jul 15 '20 11:07 saravananmnm

We have been experiencing similar issue and thanks you my colleague @JanKn not upgrading the app on his iOS device, we realised that notifications worked on older builds. Trying various builds, I have come to the conclusion that the point it stopped working was when I upgraded my macOS to Catalina.

I am tempted to downgrade to Mojave to see if that really was the cause. At present nothing I have tried has worked with current xcode / macOS to build the app

hermitdave avatar Jul 15 '20 12:07 hermitdave

@robrichardson13 Thanks for your solution, I did not realize that by disabling method swizzling I had to implement or call the functions that Firebase Message was handling in the background. In addition to the above, I would also emphasize that people call application.registerForRemoteNotifications() in the didFinishLaunchingWithOptions method as follows:

@kmdinake You don't need to call application.registerForRemoteNotifications() because when you call _firebaseMessaging.configure() in Flutter this will call [[UIApplication sharedApplication] registerForRemoteNotifications];. You can see this if you look at the FLTFirebaseMessagingPlugin.m file in the source code. Also if you call _firebaseMessaging.requestNotificationPermissions(); this will call [[UIApplication sharedApplication] registerForRemoteNotifications]; for you as seen here, FLTFirebaseMessagingPlugin.m

I conclude that if the firebase can deliver notifications when app is in foreground, then it has the apn token registered successfully on its backend. @robrichardson13 Am I right about this conclusion?

@FernandoUFS FCM notifications being received in the foreground does NOT mean that the APN token is registered successfully. My assumption is that FCM in the foreground uses some sort of Socket to deliver in the foreground and uses the iOS APNS (Remote Notifications) for background delivery. So if background delivery isnt working, I would assume it means that the APN token is never being sent to FCM correctly.

@curlyeto try setting your .plist to the following to disable swizzling. Setting to a string value will not disable.

<key>FirebaseAppDelegateProxyEnabled</key>
<false/>

robrichardson13 avatar Jul 16 '20 18:07 robrichardson13

@robrichardson13 thanks for answering. I assigned a false value to FirebaseAppDelegateProxyEnabled. I am sending a notification from postman. When the application is open, response data type. When it is closed, reponse notificaiton type.

Postman json

{
	"to":"token",
	"data":{
		"title":"Data",
		"body":"data1",
		"photo":"https://i4.hurimg.com/i/hurriyet/75/750x422/5e5771550f254405d052eb10.jpg"
	},
	"notification":{
		"title":"Notification",
		"body":"Notification1",
		"photo":"https://i4.hurimg.com/i/hurriyet/75/750x422/5e5771550f254405d052eb10.jpg"
	}
}
_fcm.configure(onMessage: (Map<String, dynamic> message) async {
print("onMessage tetkilendi: $message");
showNotification(message);
},
onBackgroundMessage: Platform.isIOS?null:myBackgroundMessageHandler,
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch tetiklendi: $message");
showNotification(message);
},
onResume: (Map<String, dynamic> message) async {
print("onResume tetiklendi: $message");
showNotification(message);
},
);

static void showNotification(Map<String,dynamic> message)async{

var largeIconPath = Platform.isIOS?await NotificationHandler()._downloadAndSaveFile(message["photo"], 'largeIcon'):
    await NotificationHandler()._downloadAndSaveFile(message["data"]["photo"], 'largeIcon');
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
      '0',
      'Mesaj Bildirimleri',
      'Gelen Mesajlar',
      largeIcon: FilePathAndroidBitmap(largeIconPath),
      styleInformation: MediaStyleInformation(),
    );
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
Platform.isIOS?await flutterLocalNotificationsPlugin.show(0, message["title"], message["body"], platformChannelSpecifics):
await flutterLocalNotificationsPlugin.show(0, message["data"]["title"], message["data"]["body"], platformChannelSpecifics);
}

I want the data type from the data postman in the background. I've been dealing for 4 or 5 days and I couldn't solve the problem

curlyeto avatar Jul 16 '20 20:07 curlyeto

@curlyeto I have been running into a situation where if the code fails in the onMessage, onResume functions, that the application will not report the error. Is the error happening in an isolate?

Could you try stripping down the sendNotifications function to just print to console? Also, I ended up using conditional logic around the message map using message.containsKey('data') etc.

mintymac avatar Jul 21 '20 18:07 mintymac

Hi guys, after doing everything, the notification worked again, I had a particular problem that I didn't notice. I have a common package shared between projects, and the firebase_messaging, and all configuration was there. We removed firebase_messaging from project's pubspec.yml since it was on our own package:

dependencies:
  common:
    path: ../../common/
  (other packages, but not firebase_messaging) ...

I just added it again to the main project's pubspec.yml, also I did the same thing as @kmdinake and @robrichardson13 overriding those methods. Now firebase can deliver notifications in background. I didn't even remove the overrode code on iOS because it's working and tomorrow we will launch a new version. But it seems like the problem was just that.

FernandoUFS avatar Jul 22 '20 17:07 FernandoUFS

Hi guys, @mintymac thanks for your answer. On message, on resume funtions is working. I added showNotficaiton function inside print but not working in the backgorund. When I open the app when I send a notification in the background, the on message function works.

  static void showNotification(Map<String,dynamic> message)async{
      print("Show notfication runing ${message}");
      // personel message
      var largeIconPath = Platform.isIOS?await NotificationHandler()._downloadAndSaveFile(message["photo"], 'largeIcon'):
      await NotificationHandler()._downloadAndSaveFile(message["data"]["photo"], 'largeIcon');
      var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        '0',
        'Mesaj Bildirimleri',
        'Gelen Mesajlar',
        largeIcon: FilePathAndroidBitmap(largeIconPath),
        styleInformation: MediaStyleInformation(),
      );
      var iOSPlatformChannelSpecifics =IOSNotificationDetails();
      var platformChannelSpecifics = NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
      Platform.isIOS?await flutterLocalNotificationsPlugin.show(0, message["title"], message["body"], platformChannelSpecifics,):
      await flutterLocalNotificationsPlugin.show(0, message["data"]["title"], message["data"]["body"], platformChannelSpecifics,);
  }

App Delegate.swift

import UIKit
import Flutter
import Firebase
import FirebaseMessaging

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {

    FirebaseApp.configure()
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
           let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
           print("==== didRegisterForRemoteNotificationsWithDeviceToken ====")
           print(deviceTokenString)
           Messaging.messaging().apnsToken = deviceToken
   }
}

Firebase request json

{
	"to":"token",
	"data":{
		"title":"Data",
		"body":"data1",
		"photo":"https://i4.hurimg.com/i/hurriyet/75/750x422/5e5771550f254405d052eb10.jpg"
	}
}

FirebaseAppDelegateProxyEnabled boolean false and string NO I tried two status but noting changing.

I want the data type from the data postman in the background. What function is triggering in the background for ios ? Where am I doing wrong ? Firebase request json format it is correct ? Can you help me @FernandoUFS , @mintymac , @robrichardson13 ?

curlyeto avatar Jul 23 '20 10:07 curlyeto

Hey guys, I've been having the same issue. Since I was using flutter_local_notification package to display notifications, I had to set the value of FirebaseProxyEnabled to false, For that reason, firebase auth wasn't working properly, so I followed these steps:https://firebase.google.com/docs/auth/ios/phone-auth#appendix:-using-phone-sign-in-without-swizzling But now the notifications, only trigger onMessage callback whenever the I open the app, And notifications show properly when the app is on the foreground. I know that firebase keeps the notifications in the queue for data message, and triggers when the app opens but for notification messages the same things are happening. I don't know what is wrong. So sad that I can't show notifications when the app is killed or on the background on iOS

adar2378 avatar Jul 23 '20 13:07 adar2378

@curlyeto Of course, happy to. From my understanding, FirebaseMessaging delivers the data message in iOS via onMessage if the app is terminated. Is there something you can accompolish with in app messaging to fill the gap for Android?

mintymac avatar Jul 23 '20 17:07 mintymac

None of the proposed resolutions are working here, not sure what to try next.

BouweCeunen avatar Jul 24 '20 22:07 BouweCeunen

@mintymac I didn't understand this sentences. " Is there something you can accompolish with in app messaging to fill the gap for Android? " . Can you explain in detail?

curlyeto avatar Jul 25 '20 09:07 curlyeto

I can confirm that It's also working for me on TestFlight.

BouweCeunen avatar Jul 25 '20 13:07 BouweCeunen