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.

What should have to do to execute FirebaseMessaging.onBackgroundMessage function in iOS?
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.
for ios:
onMessage;onBackgroundMessage;onBackgroundMessage.if app was terminated, first notification will be handled with getInitialMessage, because first notification wakes up the app
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With