firebase / flutterfire

🔥 A collection of Firebase plugins for Flutter apps.
https://firebase.google.com/docs/flutter/setup
BSD 3-Clause "New" or "Revised" License
8.58k stars 3.94k forks source link

[firebase_messaging]: <background message handler never invoked with all ways> #12758

Closed HassanSharara closed 3 months ago

HassanSharara commented 3 months ago

Is there an existing issue for this?

Are you aware of the differences between iOS and Android background message handling?

Do you have an active Apple Developer account?

Are you using a physical iOS device to test background messages?

Have you enabled "Remote Notifications" & "Background Mode" (Checking options for "Background Processing" & "Remote Notifications") in your app's Xcode project?

yes u already enabled these options

Have you created an APNs key in your Apple Developer account & uploaded this APNs key to your Firebase console?

Screenshot (1)

Have you disabled method swizzling for Firebase in your app?

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">

BGTaskSchedulerPermittedIdentifiers $(PRODUCT_BUNDLE_IDENTIFIER) com.swiacaptain.royalboardapp dev.flutter.background.refresh CADisableMinimumFrameDurationOnPhone CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleDisplayName كابتن سوية CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName royal_captain_app CFBundlePackageType APPL CFBundleShortVersionString $(MARKETING_VERSION) CFBundleSignature ???? CFBundleURLTypes CFBundleTypeRole Editor CFBundleURLName CFBundleURLSchemes com.googleusercontent.apps.1021340574332-qsg43o6vtekm1qbfbten5blrg81krg3p CFBundleTypeRole Editor CFBundleURLSchemes CFBundleVersion $(CURRENT_PROJECT_VERSION) FLTEnableImpeller FirebaseAppDelegateProxyEnabled NO GIDClientID 1021340574332-qsg43o6vtekm1qbfbten5blrg81krg3p.apps.googleusercontent.com LSApplicationQueriesSchemes comgooglemaps baidumap iosamap waze yandexmaps yandexnavi citymapper mapswithme osmandmaps dgis qqmap here-location tomtomgo copilot com.sygic.aura LSRequiresIPhoneOS NSAllowsArbitraryLoads NSAllowsArbitraryLoadsForMedia NSAllowsArbitraryLoadsForMediaUsageDescription NSAllowsArbitraryLoadsInWebContent NSAllowsArbitraryLoadsInWebContentUsageDescription NSAppTransportSecurity NSExceptionDomains googleapis.com NSExceptionAllowsInsecureHTTPLoads NSIncludesSubdomains NSCameraUsageDescription My royal_captain_app App needs to access the Camera for Uploading Cover and profile Markets Accounts and also for uploading user profile Account photo and for recording products. NSExceptionDomains googleapis.com NSExceptionRequiresForwardSecrecy NSIncludesSubdomains NSTemporaryExceptionAllowsInsecureHTTPLoads NSTemporaryExceptionMinimumTLSVersion TLSv1.1 NSLocationAlwaysAndWhenInUseUsageDescription Your location is required for matching customer requests and captains locations to get the nearest customer to the nearest captain NSLocationAlwaysUsageDescription Your location is required for matching customer requests and captains locations to get the nearest customer to the nearest captain NSLocationTemporaryUsageDescriptionDictionary Your location is required for matching customer requests and captains locations to get the nearest customer to the nearest captain NSLocationUsageDescription Your location is required for matching customer requests and captains locations to get the nearest customer to the nearest captain NSLocationWhenInUseUsageDescription Your location is required for matching customer requests and captains locations to get the nearest customer to the nearest captain NSMicrophoneUsageDescription My App needs to access the MicroPhone for recording Products and their Properties for Representative. NSPhotoLibraryUsageDescription My royal_captain_app App needs to access the Photo for Uploading Cover and profile Markets Accounts and also for uploading user profile Account photo. UIApplicationExitsOnSuspend UIApplicationSupportsIndirectInputEvents UIBackgroundModes fetch location processing remote-notification UILaunchStoryboardName LaunchScreen UIMainStoryboardFile Main UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIViewControllerBasedStatusBarAppearance com NSTemporaryExceptionAllowsInsecureHTTPLoads net NSTemporaryExceptionAllowsInsecureHTTPLoads org NSTemporaryExceptionAllowsInsecureHTTPLoads

Are you sending messages to your app from the Firebase Admin SDK?

$messaging = FirestoreDBController::messaging();

    $royal_data['click_action']='FLUTTER_NOTIFICATION_CLICK';
    $androidConfig = AndroidConfig::fromArray([
        'ttl' => '3600s',
        'priority' => 'normal',
        'notification' => [
            'title'=>$title,
            'body'=>$body,
            'click_action' => 'FLUTTER_NOTIFICATION_CLICK',
            'sound'=>'default',
            "icon" => "ic_stat_name",
        ],]);
    $apnsConfig = ApnsConfig::fromArray([
        'headers' => [
            'apns-priority' => '10',
            //  'apns-push-type'=>'background'
        ],
        'payload' => [
            'aps' => [
                'mutable-content'=>1,
                "content-available"=>1,
                "sound"=>"default"

            ],
            'data'=>$royal_data,
            'click_action' => 'FLUTTER_NOTIFICATION_CLICK',
        ],]);

        $message= 
        CloudMessage::new()
        ->withNotification(
            [
                'title'=>$title,
                'body'=>$body
            ]
        ) 
    ->withApnsConfig($apnsConfig)
    ->withAndroidConfig($androidConfig)
    ->withData($royal_data);
    $report =  $messaging->sendMulticast($message,$tokens);

Have you requested permission from the user to receive notifications?

Have you used the 'Console' application on your macOS device to check if the iOS device's system is throttling your background messages?

Hassan Sharara, [5/8/2024 2:21 PM] Sandbox error 14:16:25.662225+0300 kernel Sandbox: Runner(1031) deny(1) iokit-get-properties iokit-class:AGXAcceleratorG12P_B0 property:SCMVersionNumber Sandbox error 14:16:25.662285+0300 kernel Sandbox: Runner(1031) deny(1) iokit-get-properties iokit-class:AGXAcceleratorG12P_B0 property:SCMBuildTime Sandbox error 14:16:25.662341+0300 kernel Sandbox: Runner(1031) deny(1) iokit-get-properties iokit-class:AGXAcceleratorG12P_B0 property:IOPowerManagement Sandbox error 14:16:25.662398+0300 kernel Sandbox: Runner(1031) deny(1) iokit-get-properties iokit-class:AGXAcceleratorG12P_B0 property:AGXTraceCodeVersion Sandbox error 14:16:25.662456+0300 kernel Sandbox: Runner(1031) deny(1) iokit-get-properties iokit-class:AGXAcceleratorG12P_B0 property:GPURawCounterBundleName Sandbox error 14:16:25.662511+0300 kernel Sandbox: Runner(1031) deny(1) iokit-get-properties iokit-class:AGXAcceleratorG12P_B0 property:GPURawCounterPluginClassName Sandbox error 14:16:25.662600+0300 kernel Sandbox: Runner(1031) deny(1) iokit-get-properties iokit-class:AGXAcceleratorG12P_B0 property:GPUConfigurationVariable UserNotificationsServer error 14:16:25.731358+0300 SpringBoard No data found at /var/mobile/Library/UserNotifications/AACFA2BF-DA41-4321-A69D-5B126E5AAA31/Categories.plist UserNotificationsServer error 14:16:25.731400+0300 SpringBoard No data found at /var/mobile/Library/UserNotifications/AACFA2BF-DA41-4321-A69D-5B126E5AAA31/Categories.plist FrontBoard error 14:16:25.768965+0300 SpringBoard [(FBSceneManager):sceneID:com.swiacaptain.royalboardapp-default] updated settings were not derived from the scene's previous settings FrontBoard error 14:16:25.768934+0300 SpringBoard [(FBSceneManager):sceneID:com.swiacaptain.royalboardapp-default] updated settings were not derived from the scene's previous settings IOGPUFamily fault 14:16:25.774477+0300 kernel trying to get apparently bogus texture handle 0 IOGPUFamily fault 14:16:25.774575+0300 kernel trying to get apparently bogus texture handle 0 NetworkStatistics error 14:16:25.806333+0300 symptomsd Suspicious packet count 222 when bytes 3326 for flow 50456 NetworkStatistics error 14:16:25.806401+0300 symptomsd Flow details for excess packet count dtappserviced TCP6 flow id 50456 (refresh) so pkts rx 222 tx 4, bytes 3326 641 count rx/tx pkts 222 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx pkts 220 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx cell 0 0 wifi 0 0 wired 0 0 desc ifidx 14 flags 0x4011008 pid 582 epid 582 uuid 126C1FD4-3C10-30AC-85D2-738FA68A631F euuid 126C1FD4-3C10-30AC-85D2-738FA68A631F pname dtappserviced NetworkStatistics error 14:16:25.806471+0300 symptomsd Suspicious packet count 222 when bytes 3326 for flow 50456 NetworkStatistics error 14:16:25.806535+0300 symptomsd Flow details for excess packet count dtappserviced TCP6 flow id 50456 (refresh) so pkts rx 222 tx 4, bytes 3326 641 count rx/tx pkts 222 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx pkts 220 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx cell 0 0 wifi 0 0 wired 0 0 desc ifidx 14 flags 0x4011008 pid 582 epid 582 uuid 126C1FD4-3C10-30AC-85D2-738FA68A631F euuid 126C1FD4-3C10-30AC-85D2-738FA68A631F pname dtappserviced NetworkStatistics error 14:16:25.806603+0300 symptomsd Suspicious packet count 222 when bytes 3326 for flow 50456 NetworkStatistics error 14:16:25.806668+0300 symptomsd Flow details for excess packet count dtappserviced TCP6 flow id 50456 (refresh) so pkts rx 222 tx 4, bytes 3326 641 count rx/tx pkts 222 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx pkts 220 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx cell 0 0 wifi 0 0 wired 0 0 desc ifidx 14 flags 0x4011008 pid 582 epid 582 uuid 126C1FD4-3C10-30AC-85D2-738FA68A631F euuid 126C1FD4-3C10-30AC-85D2-738FA68A631F pname dtappserviced

Hassan Sharara, [5/8/2024 2:21 PM] NetworkStatistics error 14:16:25.806955+0300 symptomsd Suspicious packet count 222 when bytes 3326 for flow 50456 NetworkStatistics error 14:16:25.807215+0300 symptomsd Flow details for excess packet count dtappserviced TCP6 flow id 50456 (refresh) so pkts rx 222 tx 4, bytes 3326 641 count rx/tx pkts 222 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx pkts 220 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx cell 0 0 wifi 0 0 wired 0 0 desc ifidx 14 flags 0x4011008 pid 582 epid 582 uuid 126C1FD4-3C10-30AC-85D2-738FA68A631F euuid 126C1FD4-3C10-30AC-85D2-738FA68A631F pname dtappserviced NetworkStatistics error 14:16:25.807336+0300 symptomsd Suspicious packet count 222 when bytes 3326 for flow 50456 NetworkStatistics error 14:16:25.807462+0300 symptomsd Flow details for excess packet count dtappserviced TCP6 flow id 50456 (refresh) so pkts rx 222 tx 4, bytes 3326 641 count rx/tx pkts 222 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx pkts 220 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx cell 0 0 wifi 0 0 wired 0 0 desc ifidx 14 flags 0x4011008 pid 582 epid 582 uuid 126C1FD4-3C10-30AC-85D2-738FA68A631F euuid 126C1FD4-3C10-30AC-85D2-738FA68A631F pname dtappserviced NetworkStatistics error 14:16:25.807526+0300 symptomsd Suspicious packet count 222 when bytes 3326 for flow 50456 NetworkStatistics error 14:16:25.807590+0300 symptomsd Flow details for excess packet count dtappserviced TCP6 flow id 50456 (refresh) so pkts rx 222 tx 4, bytes 3326 641 count rx/tx pkts 222 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx pkts 220 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx cell 0 0 wifi 0 0 wired 0 0 desc ifidx 14 flags 0x4011008 pid 582 epid 582 uuid 126C1FD4-3C10-30AC-85D2-738FA68A631F euuid 126C1FD4-3C10-30AC-85D2-738FA68A631F pname dtappserviced NetworkStatistics error 14:16:25.807790+0300 symptomsd Suspicious packet count 222 when bytes 3326 for flow 50456 NetworkStatistics error 14:16:25.807857+0300 symptomsd Flow details for excess packet count dtappserviced TCP6 flow id 50456 (refresh) so pkts rx 222 tx 4, bytes 3326 641 count rx/tx pkts 222 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx pkts 220 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx cell 0 0 wifi 0 0 wired 0 0 desc ifidx 14 flags 0x4011008 pid 582 epid 582 uuid 126C1FD4-3C10-30AC-85D2-738FA68A631F euuid 126C1FD4-3C10-30AC-85D2-738FA68A631F pname dtappserviced NetworkStatistics error 14:16:25.806301+0300 symptomsd Suspicious packet count 222 when bytes 3326 for flow 50456 NetworkStatistics error 14:16:25.806365+0300 symptomsd Flow details for excess packet count dtappserviced TCP6 flow id 50456 (refresh) so pkts rx 222 tx 4, bytes 3326 641 count rx/tx pkts 222 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx pkts 220 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx cell 0 0 wifi 0 0 wired 0 0 desc ifidx 14 flags 0x4011008 pid 582 epid 582 uuid 126C1FD4-3C10-30AC-85D2-738FA68A631F euuid 126C1FD4-3C10-30AC-85D2-738FA68A631F pname dtappserviced NetworkStatistics error 14:16:25.806438+0300 symptomsd Suspicious packet count 222 when bytes 3326 for flow 50456 NetworkStatistics error 14:16:25.806504+0300 symptomsd Flow details for excess packet count dtappserviced TCP6 flow id 50456 (refresh) so pkts rx 222 tx 4, bytes 3326 641 count rx/tx pkts 222 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx pkts 220 4 bytes 3326 641 cell 0 0 wifi 3326 641 wired 0 0 dup 9 ooo 0 retx 0 saved rx/tx cell 0 0 wifi 0 0 wired 0 0 desc ifidx 14 flags 0x4011008 pid 582 epid 582 uuid 126C1FD4-3C10-30AC-85D2-738FA68A631F euuid 126C1FD4-3C10-30AC-85D2-738FA68A631F pname dtappserviced

Additional context and comments

i believe that this error related to firebase sdk or apple updates and i tried countless ways to solve this

and i think this error message is related to UserNotificationsServer error 14:16:25.731358+0300 SpringBoard No data found at /var/mobile/Library/UserNotifications/AACFA2BF-DA41-4321-A69D-5B126E5AAA31/Categories.plist

TarekkMA commented 3 months ago

Please set FirebaseAppDelegateProxyEnabled to YES in your info.plist and try again.

AZDEVELOPERRB commented 3 months ago

Please set FirebaseAppDelegateProxyEnabled to YES in your info.plist and try again.

i tried that before still not working

russellwheatley commented 3 months ago

Hi @HassanSharara - what is the issue exactly? I have tested and it works fine on my apple device.

HassanSharara commented 3 months ago

Hi @HassanSharara - what is the issue exactly? I have tested and it works fine on my apple device.

the exactly issue is that FirebaseMessaging.onBackgroundMessage Handler never invoked by any way and i need to call listen to Channel Method Manually to replace this method functionality

EdsonMello-code commented 3 months ago

I have exactly the same problem, the notifications arrive even in the background but onBackgroundMessage is never called in any case.

EdsonMello-code commented 3 months ago

Any solution? because I tried everything. This is my send payload:

{
  "message": {
    "token": "token",

            "notification": {
      "title": "Notification",
      "body": "Hello World!"
    },

    "android": {
      "priority": "high"
    },
    "apns": {
      "payload": {
        "aps": {
          "content-available": 1,
                    "mutable-content": 1
        }
      },
      "headers": {

        "apns-priority": "5",

      }
    }
  }
}
ivanluizjr commented 3 months ago

I'm having the same problem, I can't find a solution, I'm going to wait for the answer to see if I can solve it here too, as I'm facing the same case as above.

TarekkMA commented 3 months ago

@HassanSharara, Can you post a complete console output.

To check the status of your push notification, please follow the steps below.

  1. Open the Console app on your Mac
  2. Select your iPhone from the devices list on the left hand side
  3. Filter messages by typing in your Bundle ID (e.g. The Firebase Messaging example app bundle ID is 'io.flutter.plugins.firebase.messaging') into the search box and pressing enter.
  4. Press the clear button to clean the history.
  5. Now send the message to your device
  6. Select all the rows on the logs & copy them, Cmd + C (not available on right-click menu)

Example of successfully delivered data-only background message Example of unsuccessfully delivered data-only background message

HassanSharara commented 3 months ago

I already Implement Native IOS Code to get passed this issue and now its working better than the firebase_messaging implementation cause my work need is to Listen to every income notification no matter if its has notification key payload or not and i wish that firebase team to fix this issue on the next versions of the plugin

EdsonMello-code commented 3 months ago

I already Implement Native IOS Code to get passed this issue and now its working better than the firebase_messaging implementation cause my work need is to Listen to every income notification no matter if its has notification key payload or not and i wish that firebase team to fix this issue on the next versions of the plugin

Can you please give me the way to implement it too as I have the same problem

HassanSharara commented 3 months ago

I already Implement Native IOS Code to get passed this issue and now its working better than the firebase_messaging implementation cause my work need is to Listen to every income notification no matter if its has notification key payload or not and i wish that firebase team to fix this issue on the next versions of the plugin

Can you please give me the way to implement it too as I have the same problem

1- you need to create static MethodChannel in flutter

  static const MethodChannel platformMethodChannel = MethodChannel('sharara_ios_background_messaging_handler');

2- secondly you need to initialize handler linked to this channel

   static Future<void> initBackgroundMessagingHandlerListener()async{
    royalPlatformBackgroundMessagingHandler.setMethodCallHandler((call)async{
      if ( call.method == "ios_messaging"){
        return await onIosBackgroundMessaging(call.arguments);
      }
    });
  }

3 - you need to call initBackgroundMessagingHandlerListener on after configuring firebase

4- generating remote message from native ios call

   static Future<dynamic> onIosBackgroundMessaging(final dynamic userInfo)async{
    if(userInfo is! Map)return;
    final RemoteMessage? remoteMessage = Constans.tryCatch<RemoteMessage>(() =>  
    RemoteMessage.fromMap(userInfo.cast()));
    if(remoteMessage == null)return;
    return await _handleBackgroundNotification(remoteMessage);
  }

6- Now we need to setup flutterChannel on native Ios Code inside your AppDelegate define an object of flutterMethodChannel

  var flutterChannel :FlutterMethodChannel

7- initialize this flutterChannel with the same name as MethodChannel was on flutter ('sharara_ios_background_messaging_handler')

example :

   if flutterChannel == nil {
          let flutterViewController:FlutterViewController
          = window?.rootViewController as! FlutterViewController
          flutterChannel  = FlutterMethodChannel(name: "sharara_ios_background_messaging_handler",
              binaryMessenger:flutterViewController.binaryMessenger
          )
      }

8- override this func on your AppDelegate example:

override  func application(
    _ application: UIApplication,
    didReceiveRemoteNotification userInfo: [AnyHashable : Any],
    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
 if flutterChannel != nil {
      flutterChannel!.invokeMethod("ios_messaging",arguments:userInfo) { _ in
         /// you can implement your code here to call whatever you want after background handler end
          completionHandler(UIBackgroundFetchResult.newData)
      }
  } else {
      completionHandler(UIBackgroundFetchResult.noData)
  }
}

9 - congratulations everything is done

EdsonMello-code commented 3 months ago

I already Implement Native IOS Code to get passed this issue and now its working better than the firebase_messaging implementation cause my work need is to Listen to every income notification no matter if its has notification key payload or not and i wish that firebase team to fix this issue on the next versions of the plugin

Can you please give me the way to implement it too as I have the same problem

1- you need to create static MethodChannel in flutter

  static const MethodChannel platformMethodChannel = MethodChannel('sharara_ios_background_messaging_handler');

2- secondly you need to initialize handler linked to this channel

 static Future<void> initBackgroundMessagingHandlerListener()async{
  royalPlatformBackgroundMessagingHandler.setMethodCallHandler((call)async{
    if ( call.method == "ios_messaging"){
      return await onIosBackgroundMessaging(call.arguments);
    }
  });
}

3 - you need to call initBackgroundMessagingHandlerListener on after configuring firebase

4- generating remote message from native ios call

 static Future<dynamic> onIosBackgroundMessaging(final dynamic userInfo)async{
  if(userInfo is! Map)return;
  final RemoteMessage? remoteMessage = Constans.tryCatch<RemoteMessage>(() =>  
  RemoteMessage.fromMap(userInfo.cast()));
  if(remoteMessage == null)return;
  return await _handleBackgroundNotification(remoteMessage);
}

6- Now we need to setup flutterChannel on native Ios Code inside your AppDelegate define an object of flutterMethodChannel

var flutterChannel :FlutterMethodChannel

7- initialize this flutterChannel with the same name as MethodChannel was on flutter ('sharara_ios_background_messaging_handler')

example :

  if flutterChannel == nil {
         let flutterViewController:FlutterViewController
         = window?.rootViewController as! FlutterViewController
         flutterChannel  = FlutterMethodChannel(name: "sharara_ios_background_messaging_handler",
             binaryMessenger:flutterViewController.binaryMessenger
         )
     }

8- override this func on your AppDelegate example:

override  func application(
    _ application: UIApplication,
    didReceiveRemoteNotification userInfo: [AnyHashable : Any],
    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
 if flutterChannel != nil {
      flutterChannel!.invokeMethod("ios_messaging",arguments:userInfo) { _ in
         /// you can implement your code here to call whatever you want after background handler end
          completionHandler(UIBackgroundFetchResult.newData)
      }
  } else {
      completionHandler(UIBackgroundFetchResult.noData)
  }
}

9 - congratulations everything is done

Thanks bro! is working now

HassanSharara commented 3 months ago

I already Implement Native IOS Code to get passed this issue and now its working better than the firebase_messaging implementation cause my work need is to Listen to every income notification no matter if its has notification key payload or not and i wish that firebase team to fix this issue on the next versions of the plugin

Can you please give me the way to implement it too as I have the same problem

1- you need to create static MethodChannel in flutter

  static const MethodChannel platformMethodChannel = MethodChannel('sharara_ios_background_messaging_handler');

2- secondly you need to initialize handler linked to this channel

 static Future<void> initBackgroundMessagingHandlerListener()async{
  royalPlatformBackgroundMessagingHandler.setMethodCallHandler((call)async{
    if ( call.method == "ios_messaging"){
      return await onIosBackgroundMessaging(call.arguments);
    }
  });
}

3 - you need to call initBackgroundMessagingHandlerListener on after configuring firebase 4- generating remote message from native ios call

 static Future<dynamic> onIosBackgroundMessaging(final dynamic userInfo)async{
  if(userInfo is! Map)return;
  final RemoteMessage? remoteMessage = Constans.tryCatch<RemoteMessage>(() =>  
  RemoteMessage.fromMap(userInfo.cast()));
  if(remoteMessage == null)return;
  return await _handleBackgroundNotification(remoteMessage);
}

6- Now we need to setup flutterChannel on native Ios Code inside your AppDelegate define an object of flutterMethodChannel

var flutterChannel :FlutterMethodChannel

7- initialize this flutterChannel with the same name as MethodChannel was on flutter ('sharara_ios_background_messaging_handler') example :

  if flutterChannel == nil {
         let flutterViewController:FlutterViewController
         = window?.rootViewController as! FlutterViewController
         flutterChannel  = FlutterMethodChannel(name: "sharara_ios_background_messaging_handler",
             binaryMessenger:flutterViewController.binaryMessenger
         )
     }

8- override this func on your AppDelegate example:

override  func application(
    _ application: UIApplication,
    didReceiveRemoteNotification userInfo: [AnyHashable : Any],
    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
 if flutterChannel != nil {
      flutterChannel!.invokeMethod("ios_messaging",arguments:userInfo) { _ in
         /// you can implement your code here to call whatever you want after background handler end
          completionHandler(UIBackgroundFetchResult.newData)
      }
  } else {
      completionHandler(UIBackgroundFetchResult.noData)
  }
}

9 - congratulations everything is done

Thanks bro! is working now

You are Welcome

EdsonMello-code commented 3 months ago

It arrives in the background, but testing it better when the app is closed in release it calls the code in the background only when I open the app again. But this is better than it was before when it wasn't even possible

HassanSharara commented 3 months ago

This the way that you could invoke your custom handler when receive a message but not the way to escape from ios throttle system You need to implement strategy to schedule your background task to get what you want or there is another violate method and also keep in mind that debug mode on real device will be dismissed when u close the app and also rhe simulator will not probably work so you need to test that on Apple store with test fly

EdsonMello-code commented 3 months ago

You are correct, it was throwing an exception and not completing the action

HassanSharara commented 3 months ago

You are correct, it was throwing an exception and not completing the action

throwing an exception because of

let flutterViewController:FlutterViewController
         = window?.rootViewController as! FlutterViewController

change as! to as?

cause when the app is terminated or there is no screen or ui to show the window object would be nil ( or null ) so it will not work if you want to use this implementation even on app is terminated you need run flutter engine on background i think if firebase team did not solve this i will build package to receive all data income from APS or firebase notifications