Flutter- firebase_messgage从v7到v11迁移 - 未被调用

发布于 2025-02-02 06:26:38 字数 4161 浏览 2 评论 0原文

我需要一些帮助来迁移我的项目。 基本上,项目现在已经有点旧了,它运行了将近3年,直到现在它是用flutter 1.22.6构建的。现在,我试图将其迁移到v2.10.3,而迁移几乎完成了。最后不工作的是iOS推送通知。

旧版本正在firebase_messaging v.7.0.3上运行,并且正常工作。 升级的颤音要求版本9.0.0或更高版本。

我已经完成了基本的代码迁移,Android还可以,但是在iOS上,我的onMessage从未调用处理程序。 推动正在交付,并在应用程序在后台时正确显示通知。但是,当它在前景时,否则我将单击该通知时,应用程序就会进入前景,但是没有触发回调。

我在日志中唯一看到的是错误: 满足路径),可行,接口:en0,ipv4,dns,dns)]

NW_ENDPOINT_HANDLER_SETE_ADAPTIVE_READLER [C6.1 216.58.212.42:443 READY CHANNEL-FLOW(满意( 通过堆栈和其他地方的大多数主题,但是这些解决方案都不适合我。 我不使用任何其他插件,例如flutter_local_notifications或类似的插件,这可能会导致故障。

最重要的代码:

flutter医生

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel unknown, 2.10.3, on macOS 11.6 20G165 darwin-x64, locale
    pl-PL)
[✓] Android toolchain - develop for Android devices (Android SDK version
    33.0.0-rc3)
[✓] Xcode - develop for iOS and macOS (Xcode 13.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.2)
[✓] VS Code (version 1.67.1)
[✓] Connected device (1 available)
[✓] HTTP Host Availability

pubspec.yaml

  firebase_core: 1.16.0
  firebase_messaging: 11.3.0
  google_ml_kit: 0.7.3

appdelegate.swift

override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
    ) -> Bool {
        disableCache();
        FirebaseConfiguration.shared.setLoggerLevel(.min)
        FirebaseApp.configure()
        self.SetupPushNotification(application: application)
    
    func SetupPushNotification(application: UIApplication) -> () {
        if #available(iOS 10, *){ UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge])
        {(granted,error) in
            if granted{
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            } else {
                print("User Notification permission denied: \(error?.localizedDescription ?? "error")")
            }
        }
        }
    }
    
    override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        NotificationDeviceToken.sharedInstance.setToken(token: tokenString(deviceToken))
     }

    override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications: \(error.localizedDescription)")
    }
    
    override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        print(userInfo)
     }

     func tokenString(_ deviceToken:Data) -> String{
         let bytes = [UInt8](deviceToken)
         var token = ""
         for byte in bytes{
             token += String(format: "%02x",byte)
         }
         return token 
     }

main.dart

void startApp(AppConfig config) async {
  // add this, and it should be the first line in main method
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  ...
}

app.dart

  void init(BuildContext context, AppCubit cubit,
      SubscriptionManager subscriptionManager) {
    await FirebaseMessaging.instance.getToken();
    FirebaseMessaging.onMessage.listen((map) {
      _log.debug('onMessage: ${map.data}');
      final push = Push(map.data, PushType.onMessage);
      _streamController.add(push);
      return Future<bool>.value(true);
    });

    FirebaseMessaging.onMessageOpenedApp.listen((map) {
      _log.debug('onMessageOpenedApp: ${map.data}');
      _startAppFromPush = true;
      final push = Push(map.data, PushType.onLaunch);
      _streamController.add(push);
      return Future<bool>.value(true);
    });
  }

信息

...
<key>FirebaseAppDelegateProxyEnabled<key/>
<false/>
...

。 提前致谢。

I need some help in migrating my project.
Basically project is a bit old now, its running for almost 3 years and until now it was built with flutter 1.22.6. Now i am trying to migrate it to v2.10.3 and migration is almost done. Last not working piece is iOS Push Notifications.

Old version is running on firebase_messaging v.7.0.3 and it's working just fine.
Upgrading flutter demands version 9.0.0 or higher.

I've done basic code migration and Android is OK, but on iOS my onMessage handler is never being called.
Push is being delivered and notification is being displayed correctly when app is in background. But when its in foreground, or i will click that notification, app comes into the foreground, but callbacks are not being triggered.

The only thing i see in logs is error like:
nw_endpoint_handler_set_adaptive_read_handler [C6.1 216.58.212.42:443 ready channel-flow (satisfied (Path is satisfied), viable, interface: en0, ipv4, dns)] unregister notification for read_timeout failed

OFC i've looked through most of topics on stack and other places, but none of these solutions worked for me.
I'm not using any other plugins, such as flutter_local_notifications or similar, which could cause faults.

Most important pieces of code:

flutter doctor

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel unknown, 2.10.3, on macOS 11.6 20G165 darwin-x64, locale
    pl-PL)
[✓] Android toolchain - develop for Android devices (Android SDK version
    33.0.0-rc3)
[✓] Xcode - develop for iOS and macOS (Xcode 13.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.2)
[✓] VS Code (version 1.67.1)
[✓] Connected device (1 available)
[✓] HTTP Host Availability

pubspec.yaml

  firebase_core: 1.16.0
  firebase_messaging: 11.3.0
  google_ml_kit: 0.7.3

AppDelegate.swift

override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
    ) -> Bool {
        disableCache();
        FirebaseConfiguration.shared.setLoggerLevel(.min)
        FirebaseApp.configure()
        self.SetupPushNotification(application: application)
    
    func SetupPushNotification(application: UIApplication) -> () {
        if #available(iOS 10, *){ UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge])
        {(granted,error) in
            if granted{
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            } else {
                print("User Notification permission denied: \(error?.localizedDescription ?? "error")")
            }
        }
        }
    }
    
    override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        NotificationDeviceToken.sharedInstance.setToken(token: tokenString(deviceToken))
     }

    override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications: \(error.localizedDescription)")
    }
    
    override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        print(userInfo)
     }

     func tokenString(_ deviceToken:Data) -> String{
         let bytes = [UInt8](deviceToken)
         var token = ""
         for byte in bytes{
             token += String(format: "%02x",byte)
         }
         return token 
     }

main.dart

void startApp(AppConfig config) async {
  // add this, and it should be the first line in main method
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  ...
}

app.dart

  void init(BuildContext context, AppCubit cubit,
      SubscriptionManager subscriptionManager) {
    await FirebaseMessaging.instance.getToken();
    FirebaseMessaging.onMessage.listen((map) {
      _log.debug('onMessage: ${map.data}');
      final push = Push(map.data, PushType.onMessage);
      _streamController.add(push);
      return Future<bool>.value(true);
    });

    FirebaseMessaging.onMessageOpenedApp.listen((map) {
      _log.debug('onMessageOpenedApp: ${map.data}');
      _startAppFromPush = true;
      final push = Push(map.data, PushType.onLaunch);
      _streamController.add(push);
      return Future<bool>.value(true);
    });
  }

Info.plist

...
<key>FirebaseAppDelegateProxyEnabled<key/>
<false/>
...

Any help will be appreciated.
Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挽清梦 2025-02-09 06:26:38

看起来我找到了解决方案。

我发现Github Flutterfire项目中开了一个问题。
主题之一与我的麻烦非常相似。

https://github.com/firebase/flutterfire/flutterfire/sissues/issues/4300 从FCM发送的每个推动都会在有效载荷中获得其他字段,称为gcm.message_id
来自APN的通知没有获得此字段。

插件firebase_messaging 从版本9到现在开始验证此字段,如果推动不包含它,则回调 onMessage and code> onMessageApeOpenedApp 未触发。

如果您面临类似的麻烦,则有2个选项:

  • 在您的APNS消息有效负载中添加缺少字段,
  • 使用Firebase_messaging插件创建自己的叉子,并在2个位置修改FLTFIREBASEMESSAGGINGINPLUGIN,在此适当的情况下。

我希望这对你们中的一些人有用。我花了很多时间研究这个问题。

Looks like I've found solutions.

I've found an issue opened in github flutterfire project.
One of topics was very similar to my trouble.
https://github.com/firebase/flutterfire/issues/4300

The thing is that every push sent from FCM gets additional field in payload called gcm.message_id.
Notifications from APNS do not get this field.

Plugin firebase_messaging starting from version 9 up to now is validating this field and if push does not contain it, callbacks onMessage and onMessageOpenedApp are not being triggered.

If You are facing similar trouble You have 2 options:

  • add missing field in Your APNS message payload
  • create Your own fork with firebase_messaging plugin and modify FLTFirebaseMessagingPlugin in 2 places, where proper if statements are located.

I hope this will be useful to some of You. I've spent a lot of time researching this issue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文