Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 821
Md Mahmudul Islam Avatar asked Jun 25 '26 18:06

Md Mahmudul Islam


2 Answers

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.

like image 133
Ayan Das Avatar answered Jun 28 '26 18:06

Ayan Das


Client

for ios:

  1. foreground - onMessage;
  2. background - onBackgroundMessage;
  3. terminated - onBackgroundMessage.

BUT

if app was terminated, first notification will be handled with getInitialMessage, because first notification wakes up the app

Server

exapmle of config:

       messaging.Message(
            token=recipient['fcm_token'], data={**message_data, 'user_id': str(recipient['user_id'])},
            notification=messaging.Notification(
                title=message_data['title'], body=message_data['body'], image=message_data['image'],
            ),
            fcm_options=messaging.FCMOptions(analytics_label=message_data.get('analytics_label', None)),
            apns=messaging.APNSConfig(
                payload=messaging.APNSPayload(
                    aps=messaging.Aps(
                        content_available=True,
                    ),
                ),
                headers={'apns-priority': '5'},
            ),
        )

need content_available=True and maybe headers={'apns-priority': '5'}

like image 41
Kirill Shabanov Avatar answered Jun 28 '26 17:06

Kirill Shabanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!