首页 > 解决方案 > Flutter FirebaseMessaging onMessage 不起作用

问题描述

我正在尝试向 IOS 颤振应用程序推送通知。我的颤振主循环如下所示:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp();

  print(await FirebaseMessaging.instance.getToken());

  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true, // Required to display a heads up notification
    badge: true,
    sound: true,
  );

  runApp(MyApp());
}

MyApp() 的 initState() 看起来像这样:

@override
  void initState() { 
    super.initState();

    FirebaseMessaging messaging = FirebaseMessaging.instance;

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Got a message whilst in the foreground!');
      print('Message data: ${message.data}');

      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
      }
    });
  }

我无法让任何 FirebaseMessaging 流工作。onMessage/onMessageOpenedApp/onBackgroundMessage() 不会工作,但如果应用程序关闭,我可以推送通知。但上述流仍然没有任何内容。

我通过这个 python 代码推送通知:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import messaging

cred = credentials.Certificate("auth.json")
app = firebase_admin.initialize_app(cred)

topic = 'test'

apns_config = messaging.APNSConfig(
    payload=messaging.APNSPayload(
        messaging.Aps(
            mutable_content=False,
            sound=messaging.CriticalSound('default')
        )
    )
)

notification = messaging.Notification(
    title="FCM Message",
    body="This is a Firebase Cloud Messaging Topic Message!"
)

# See documentation on defining a message payload.
message = messaging.Message(
    data={
        'score': '850',
        'time': '2:45',
    },
    notification=notification,
    #topic=topic,
    token="token_of_device",
    apns=apns_config
)


response = messaging.send(message, app=app)

print('Successfully sent message:', response)

有没有办法解决这个问题?提前致谢。

标签: firebaseflutterfirebase-cloud-messaging

解决方案


要在 IOS 上测试通知,您必须具备:

Mac(从 XCode 运行),iPhone(不能在模拟器上运行,因为这是苹果的政治:“从用户那里获得所有的钱”),苹果开发帐户(100 美元/年),设置证书,询问用户获取权限,然后在真实的 Iphone 设备上进行测试


推荐阅读