'Flutter: FirebaseMessaging.onBackgroundMessage never execute in iOS

I want to execute some code in onBackgroundMessage when app is in background or killed.

I am getting push notifications as aspected but onBackgroundMessage function is never executed in iOS. It works perfectly in Android devices.

Here is my code:

Future<void> _backgroundHandler(RemoteMessage message) async{
  await Firebase.initializeApp();

  dynamic isCall = message.data['status'];

  print(isCall);

  if(isCall == 'call'){
   //.....
  }else{
    NotificationHandler.flutterLocalNotificationPlugin.cancelAll();
  }

  FirebaseNotifications.showNotification(message.data);
}



Future<void> main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_backgroundHandler);

  runApp(const MyApp());
}

I also add APNs and add capabilities Background Modes and Push Notifications. Tested on real device.

enter image description here

What should have to do to execute FirebaseMessaging.onBackgroundMessage function in iOS?



Solution 1:[1]

You need to set content-available to true in your notification payload from backend. This value let OS know that some data is available with the notification and allow that callback to be executed even when your app is in terminated state.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ayan Das