Flutter firebase_messaging Background Handler not Executing but Messages are Arriving on iOS

Viewed 2892

I've got firebase_messaging 9.1.0 receiving and showing both my Android and iOS apps notifications when the app is in the foreground, in the background, and closed. However on iOS the background handler future doesn't appear to be executing. I'm running the firebase_messaging_example app it doesn't print 'Handling a background message ${message.messageId}' when running in the background.

Background fetch and remote notifications are checked in xcode.

I've tried:

Sending notifications with and without clickAction: "FLUTER_NOTIFICATION_CLICK"

With and without

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

in info.plist

With and without background processing checked in xcode.

I'd like the background handler to execute some code that sets a badge on the app launcher icon. Does anyone know how to get the handler to work with iOS or another way to set a badge on the launcher icon when the app is closed?

1 Answers

Based on your replies in the comments section, please try to use this:

This is your top level function, above of void main()

 Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
     if (Firebase.apps.isEmpty) await Firebase.initializeApp();
     print('Handling a background message ${message.messageId}');
    }


handleNotifications() async {
FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(badge: true, alert: true, sound: true);//presentation options for Apple notifications when received in the foreground.

FirebaseMessaging.onMessage.listen((message) async {
print('Got a message whilst in the FOREGROUND!');
return;
}).onData((data) {
print('Got a DATA message whilst in the FOREGROUND!');
print('data from stream: ${data.data}');
});

FirebaseMessaging.onMessageOpenedApp.listen((message) async {
  print('NOTIFICATION MESSAGE TAPPED');
return;
}).onData((data) {
print('NOTIFICATION MESSAGE TAPPED');
print('data from stream: ${data.data}');
});

FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  FirebaseMessaging.instance
      .getInitialMessage()
      .then((value) => value != null ? _firebaseMessagingBackgroundHandler : false);
return;
}

Then, Inside void main, write it like this:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  handleNotifications(); 
  runApp(MyAppState());
}

Please let me know what happens after this, but this is most likely going to solve your problem.

Related