Skip to content

🐛 [firebase_messaging] IOS firebaseMessagingBackgroundHandler never called ! #9563

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
hatemragab opened this issue Sep 18, 2022 · 25 comments
Assignees
Labels
platform: ios Issues / PRs which are specifically for iOS. plugin: messaging resolution: user This was a user issue, e.g. invalid configuration or code. type: bug Something isn't working

Comments

@hatemragab
Copy link

hatemragab commented Sep 18, 2022

i have created a repo to prove that the swift project background handler works in the native app
but in flutter firebase messaging it not working
and always getInitialMessage returns null on iOS #9462
prove_bacground_handler_ios_works
issue number #6290
say that the example of #9292
fix it but actually, the bug still exists
i have run the example here official package example
example
the same bug exists because of the project written in objective c I cant create a pull request to fix it #9562
since it works in the native swift project!
prove_bacground_handler_ios_works

```flutter doctor -v,```
[✓] Flutter (Channel stable, 3.3.0, on macOS 12.5.1 21G83 darwin-arm (Rosetta),
    locale en-EG)
    • Flutter version 3.3.0 on channel stable at /Users/hatemragap/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision ffccd96b62 (3 weeks ago), 2022-08-29 17:28:57 -0700
    • Engine revision 5e9e0e0aa8
    • Dart version 2.18.0
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /Users/hatemragap/Library/Android/sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build
      11.0.12+0-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 13F100
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build
      11.0.12+0-b1504.28-7817840)

[✓] IntelliJ IDEA Ultimate Edition (version 2022.2.1)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.71.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.48.0

Scanning for devices is taking a long time...[✓] Connected device (4 available)
    • JKM LX1 (mobile) • DEF4C19220000662                         •
      android-arm64  • Android 9 (API 28)
    • iPhone (mobile)  • ceb98944a0e537f3303f2bd68c1f568d22ed0ca1 • ios
      • iOS 14.6 18F72
    • macOS (desktop)  • macos                                    • darwin-arm64
      • macOS 12.5.1 21G83 darwin-arm (Rosetta)
    • Chrome (web)     • chrome                                   •
      web-javascript • Google Chrome 105.0.5195.125

[✓] HTTP Host Availability
    • All required HTTP hosts are available

@darshankawar
Copy link

i have run the example here offlical pacakge example
example
same bug exist because of the project written in objective c

@hatemragab Can you provide flutter doctor -v, plugin version and console logs which shows the current behavior ?

@darshankawar darshankawar added blocked: customer-response Waiting for customer response, e.g. more information was requested. and removed Needs Attention This issue needs maintainer attention. labels Sep 19, 2022
@hatemragab
Copy link
Author

@darshankawar thanks for your time
i have updated the question i use firebase messaging v firebase_messaging 13.0.2
current behavior doesn't show any console log i also try it in debug and profile and release mode nothing show in the log i also try to set some bool in sharedPref and read this value in start-up but this value has not changed this means the invoke of the firebaseMessagingBackgroundHandler never called on the other side i have created swift project my xcode v is Version 13.4.1 (13F100) and there is a method i follow the apple documentation here and successfully set up didReceiveRemoteNotification
it called when the fcm send message as shown here prove_bacground_handler_ios_works

@google-oss-bot google-oss-bot added Needs Attention This issue needs maintainer attention. and removed blocked: customer-response Waiting for customer response, e.g. more information was requested. labels Sep 19, 2022
@darshankawar
Copy link

Is the app minimized or terminated when you try sending notifications that they are not received ?

@darshankawar darshankawar added blocked: customer-response Waiting for customer response, e.g. more information was requested. and removed Needs Attention This issue needs maintainer attention. labels Sep 19, 2022
@hatemragab
Copy link
Author

hatemragab commented Sep 19, 2022

Two cases not received
Please try to run the firebase example
And my repo example minimize the app so you can see the logs

@google-oss-bot google-oss-bot added Needs Attention This issue needs maintainer attention. and removed blocked: customer-response Waiting for customer response, e.g. more information was requested. labels Sep 19, 2022
@darshankawar
Copy link

Yes, I ran the messaging example on iOS device using latest master version of the framework. Updated the fcm token in send-message.js, kept the app minimized and then ran npm run send-message 5 times for which the notification was received as shown in below video, along with onBackgroundHandler was invoked everytime as below:

RPReplay-Final1663584024.MP4
flutter: Handling a background message 1663583988040221
flutter: Handling a background message 1663583996074157
flutter: Handling a background message 1663584002349018
flutter: Handling a background message 1663584008712037
flutter: Handling a background message 1663584014877747

When you run the same plugin example, do you not get same behavior as above ?

@darshankawar darshankawar added blocked: customer-response Waiting for customer response, e.g. more information was requested. and removed Needs Attention This issue needs maintainer attention. labels Sep 19, 2022
@hatemragab
Copy link
Author

I will upgrade flutter sdk to lasted version
And share the steps i have done while run the official example

@google-oss-bot google-oss-bot added Needs Attention This issue needs maintainer attention. and removed blocked: customer-response Waiting for customer response, e.g. more information was requested. labels Sep 19, 2022
@darshankawar darshankawar added blocked: customer-response Waiting for customer response, e.g. more information was requested. and removed Needs Attention This issue needs maintainer attention. labels Sep 19, 2022
@hatemragab
Copy link
Author

I will explains in details what i have done while testing

  1. Run git clone https://github.com/firebase/flutterfire
  2. melos bs
  3. create new notifications key on apple developer account
  4. under /flutterfire/packages/firebase_messaging/firebase_messaging/example/ change the bundle identifier for ios so i can run it on my apple developer account
  5. run flutterfire configure to handle and create new firebase account
  6. upload my APNs SSL certificate to firebase so i can send notifications
  7. then generate new google-services.json and put it in the scripts folder in the example
  8. run the app on my iphone ios v 14.6 get my fcm token and updated the send-message.js
  9. at this point i can receive notifications on my ios iPhone
  10. i have minimized the app in background and send notification it arrive but the print('Handling a background message ${message.messageId}'); never invoked it works in android good
  11. i have uploaded video here https://drive.google.com/file/d/1hzpiQXQRSYbU-extiqAwUwpCotmHryLs/view?usp=sharing
    image

image

@google-oss-bot google-oss-bot added Needs Attention This issue needs maintainer attention. and removed blocked: customer-response Waiting for customer response, e.g. more information was requested. labels Sep 19, 2022
@darshankawar
Copy link

Thanks for the effort in sharing these details and also for your patience on this @hatemragab
I followed all steps as mentioned and this time I ran the app from Xcode instead of AS, but the result have been same as expected. I am getting backgroundHandler log in the console as expected everytime I run the script with success.

I tried in two ways. First without giving permission -> sent notification through script which were received properly as below:

2022-09-20 15:34:10.957993+0530 Runner[1209:60600] flutter: FCM Token: e_GdLnN6PEfyklOPpSoDM9:APA91bHPhNDXaFZvUcM7G8pbDpdLkP6UXH9I7ah-7owMeI2mbyHhLP4AWJiGrTHKyX1_JofKPyUyeipmN2gPZfUlOD9rLDiNdwmuksqFHTizGK4lNzGVfZmsIub-hFaHeBnofz4Dkhc4
2022-09-20 15:34:10.962123+0530 Runner[1209:60600] flutter: Token monitor set null
2022-09-20 15:35:34.507333+0530 Runner[1209:60600] flutter: A new onMessage event was published!
2022-09-20 15:35:41.541299+0530 Runner[1209:60600] flutter: Handling a background message 1663668341020206
2022-09-20 15:35:51.784956+0530 Runner[1209:60600] flutter: Handling a background message 1663668351094787
2022-09-20 15:36:00.295771+0530 Runner[1209:60600] flutter: Handling a background message 1663668359687078
2022-09-20 15:36:14.126933+0530 Runner[1209:60144] [BackgroundTask] Background Task 29 ("Flutter debug task"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.

Second, after giving permission and then ran script thrice, for which below are the logs:

2022-09-20 15:37:10.936081+0530 Runner[1209:60600] flutter: A new onMessage event was published!
2022-09-20 15:37:19.934195+0530 Runner[1209:60600] flutter: Handling a background message 1663668439554110
2022-09-20 15:37:27.675842+0530 Runner[1209:60600] flutter: Handling a background message 1663668447310647
2022-09-20 15:37:37.985803+0530 Runner[1209:60600] flutter: Handling a background message 1663668457283378
2022-09-20 15:37:52.196020+0530 Runner[1209:60144] [BackgroundTask] Background Task 68 ("Flutter debug task"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.

Having verified as above, but based on your report and observation, I am going ahead and keeping this issue open and label for further insights from the team to see what they think of this entire background handler not working scenario.

@darshankawar darshankawar added plugin: messaging platform: ios Issues / PRs which are specifically for iOS. and removed Needs Attention This issue needs maintainer attention. triage Issue is currently being triaged. labels Sep 20, 2022
@hatemragab
Copy link
Author

so wired on the other hand if i implement this code in my ios native project

import UIKit
import Flutter
import flutter_local_notifications
import GoogleMaps
import Firebase
import FirebaseMessaging
import FirebaseCore
import UserNotifications
import Alamofire


@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate,MessagingDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("------")
    FirebaseApp.configure()
   //   Messaging.messaging().delegate = self
      UNUserNotificationCenter.current().delegate = self
   
      application.registerForRemoteNotifications()
      GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
//    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
//        print(fcmToken!)
//    }
    override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
         print(userInfo)
         print("didReceiveRemoteNotificationdidReceiveRemoteNotification called")
          let center = UNUserNotificationCenter.current()
          let content = UNMutableNotificationContent()
          content.title = "Hi"
          content.body = "body here"
          content.sound = .default
          let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
          let requestx = UNNotificationRequest(identifier: "testx", content: content, trigger: trigger)
          center.add(requestx){
              (error) in
              if error != nil {
                  print(error)
              }
          }
        let myurl = URL(string: "http://192.168.1.5:3000/api/v1/channel/63208af74844757e493c93a6/deliver")!
        var httpRequest = URLRequest(url:myurl)
        httpRequest.httpMethod = "PATCH"
        httpRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
        httpRequest.addValue("application/json", forHTTPHeaderField: "Accept")
        httpRequest.addValue("Bearer Y29tIiwic3ViIjoiYWNjZXNzIn0.DFiaZ0JnJYvOHamyQm_RK5JJzGIJWPDGCbvttuLDji4", forHTTPHeaderField: "Authorization")
      
        AF.request(httpRequest).responseJSON { request, response, JSON, error in
            print(error)
            print(response)
            print(JSON)
            completionHandler(.newData)
        }
    
//        var connection: NSURLConnection = NSURLConnection(request: httpRequest, delegate: self, startImmediately: true)!
//        connection.start()
//        completionHandler(.newData)
    }
}

the didReceiveRemoteNotification
get invoked correctly in the background! with the same configrations

@hatemragab
Copy link
Author

@russellwheatley hope you can help me there
thanks for your time @darshankawar

@iosephmagno
Copy link

@hatemragab we face this issue only as described in #9536. But I just saw you are testing on iphone old models and we have not tested on that phones yet. Can you test also on a recent iphone?

@hatemragab
Copy link
Author

@hatemragab we face this issue only as described in #9536. But I just saw you are testing on iphone old models and we have not tested on that phones yet. Can you test also on a recent iphone?

Okay I will try but any way it should working on this version

@iosephmagno
Copy link

@hatemragab can we see your notification json?

@hatemragab
Copy link
Author

@hatemragab can we see your notification json?

  .messaging()
  .sendToDevice(
    [token],
    {
      data: {
        foo:'bar',
      },
      notification: {
        title: 'A great title',
        body: 'Great content',
      },
    },
    {
      // Required for background/terminated app state messages on iOS
      contentAvailable: true,
      // Required for background/terminated app state messages on Android
      priority: 'high',
    }
  )

@iosephmagno
Copy link

Try this. At first glance, you are missing push-type background

Notification Sample Payload:

{
admin.messaging().send({
token: "device token",
data: {

"title": "Silent Notification",

"body": "Hello World!",
},
// Set Android priority to "high"
android: {
priority: "high",
},
// Add APNS (Apple) config
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
"apns-push-type": "background",
"apns-priority": "5", // Must be 5 when contentAvailable is set to true.
"apns-topic": "com.******.presence", // bundle identifier
},
},
});

@hatemragab
Copy link
Author

I have updated and same bug here

admin
  .messaging()
  .sendMulticast(
    {
      notification:{
        body:"xx",
        title:"dff"
      },
      tokens: [token],
      data: {
        "foo": "foox"
      },
      apns: {
        headers: {
          "apns-push-type": "background",
          "apns-priority": "5",
          "apns-topic": "io.flutter.plugins.firebase.messaging.updated", // bundle identifier
        },
        payload: {
          aps: {
            contentAvailable: true,
          }
        }
      }
    }
  )

@iosephmagno
Copy link

Then it should be device settings.
Go to General / Background App Refresh.
Check that your app is enabled here.

@hatemragab
Copy link
Author

16637813233568429627615427469688
Already enabled
On the other hand if i just implement the native swift
didReceiveRemoteNotification
It working good!!😅😳

@rikeealmeida
Copy link

Im facing same exactly problem in ios 15.6, the background handler not ever invoked

@iosephmagno
Copy link

Yea I forgot about it 😊 Maybe #9581 nailed it and this is the same issue which behaves differently on different iphone models / ios versions. That would also explain why @darshankawar cannot reproduce issue on his device.

@russellwheatley russellwheatley self-assigned this Sep 22, 2022
@russellwheatley
Copy link
Member

Hello everyone, we’ve reviewed the issues opened for iOS background messages and we want to make our position clear.

Android and iOS handle background messaging differently. The decision made by the iOS operating system whether messages reaches the relevant iOS event handler (and subsequently received by the Dart background messaging handler) is based on a number of criteria, such as: CPU usage, priority level (data-only messages are considered “low priority” by iOS, android does not), battery level, amount of messages being received by the app, background/terminated application state, etc. This is a fundamental difference between the platforms, and you need to be aware of them when designing your application.

One solution suggested for iOS data-only messages unreliability has been to add a NotificationExtension. But this will still not create parity with Android as you will still have to include a notification with your message (therefore not data-only). It will still render the original notification if you do not update/mutate the notification that comes through the system in a timely manner. We are not currently considering this as a solution due to these limitations.

We also will not support non-FCM messages from third party packages. We specifically only support messages received from the Firebase APIs since we cannot guarantee that messages received from third party packages will not have any unintended side-effects on other Firebase products such as messaging delivery reporting and Analytics data.

To help us triage and locate genuine issues that need to be addressed we have created a specific issue template for iOS background messages. If you believe you still have an issue that needs to be addressed, please create a new issue following this template.

I will be closing this issue in favor of raising a new issue with the new template above. This template will help you provide us with all the information we need to investigate a potential issue with background messaging on iOS.

@darshankawar darshankawar added the resolution: user This was a user issue, e.g. invalid configuration or code. label Sep 27, 2022
@scalz
Copy link

scalz commented Sep 28, 2022

I can understand the team decision, but unfortunately I think this doesn't completely solve the problem.
So, I'm gonna use another plugin for FCM, as my users need reliable and customized notifications on iOS.

@iosephmagno just in case you did'nt know, the developer of Awesome Notifications plugin (a local notif plugin) released yesterday his own Awesome Notification FCM plugin. He created it so both plugins are tailored to fit well together in a timely manner. This should be compatible with mutable content flag etc.
This new plugin is in alpha stage. There is a Discord available if you need more infos :)

@iosephmagno
Copy link

@scalz Thanks for the advice. We are in touch with Rafael and already sponsored Awesome.
To us it is important to first understand what firebase_messaging team will decide to do.

Due to limitations on iOS, more and more companies are deciding not to use FCM on iOS (see here https://pub.dev/packages/push). But I think it would be best if we could use firebase_messaging for both platforms.

@iosephmagno
Copy link

iosephmagno commented Sep 28, 2022

@darshankawar @russellwheatley can I suggest to add this discovery about "Notifications and Encryption on iOS" in your Readme? It took several weeks for us to understand we had an issue on iOS. Basically, you can warn people that if they use encrypted content in their notifications, then firebase_messaging is currently not a valid solution for iOS. Without encryption, they can use remote-notification on iOS (to avoid throttling) and either remote-notifican or silent-notifications on android, and we've found that the plugin works great in that scenario.

@hatemragab
Copy link
Author

I can understand the team decision, but unfortunately I think this doesn't completely solve the problem. So, I'm gonna use another plugin for FCM, as my users need reliable and customized notifications on iOS.

@iosephmagno just in case you did'nt know, the developer of Awesome Notifications plugin (a local notif plugin) released yesterday his own Awesome Notification FCM plugin. He created it so both plugins are tailored to fit well together in a timely manner. This should be compatible with mutable content flag etc. This new plugin is in alpha stage. There is a Discord available if you need more infos :)

thanks for advice
is the Discord public please send me the join link I am looking forward to using it we can't use fcm because of Ios background handler not working we need to decrypt and show local notification while there are silent notifications pushed

@firebase firebase locked and limited conversation to collaborators Oct 28, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
platform: ios Issues / PRs which are specifically for iOS. plugin: messaging resolution: user This was a user issue, e.g. invalid configuration or code. type: bug Something isn't working
Projects
None yet
Development

No branches or pull requests

7 participants