首页 > 解决方案 > 当应用程序处于后台时,不会通过 FCM 调用 iOS 上的后台消息处理程序

问题描述

谁能告诉我为什么我不能在 iOS 中收到 onBackgroundMessage 的触发器,但我可以通过 FCM 收到通知,因此如果我点击通知 onMessageOpenedApp 就会被触发。我将如何触发 onBackgroundMessage?与 Android 相比,一切正常。

这是我的代码

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  if (Firebase.apps.isEmpty) await Firebase.initializeApp();
  print('Handling a background message ${message.data['id']}');
}

handleNotifications() async {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
  NotificationSettings settings = await _firebaseMessaging.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );

  print('User granted permission: ${settings.authorizationStatus}');

  _firebaseMessaging.getToken().then((String token) async {
    assert(token != null);
    print(token);
    final sessionPrefs = await SharedPreferences.getInstance();
    if (Platform.isAndroid) {
      sessionPrefs.setString('token', token);
      sessionPrefs.setString('platform', 'android');
    } else if (Platform.isIOS) {
      sessionPrefs.setString('token', token);
      sessionPrefs.setString('platform', 'ios');
    }
  });
  FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(badge: false, alert: false, sound: true); //presentation options for Apple notifications when received in the foreground.

  FirebaseMessaging.onMessage.listen((message) async {
    print('Got a message whilst in the FOREGROUND!');
    return;
  }).onData((data) async {
    print('Got a DATA message whilst in the FOREGROUND!');
    print('data from stream: ${data.data['id']}');
  });

  FirebaseMessaging.onMessageOpenedApp.listen((message) async {
    print('NOTIFICATION MESSAGE TAPPED');
    return;
  }).onData((data) async {
    print('NOTIFICATION MESSAGE TAPPED');
    print('data from streamOpen: ${data.data}');
  });

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  FirebaseMessaging.instance.getInitialMessage().then((value) => value != null ? _firebaseMessagingBackgroundHandler : false);
  return;
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  handleNotifications();
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      initialRoute: '/',
      home: session //Menu if the user has not loged out the app else Home
          ? Menu()
          : HomePage(), // CONDITION FOR CHECKING IF THE SESSION IS TRUE OR FALSE
    ),
  );
}

标签: iosflutterfirebase-cloud-messaging

解决方案


推荐阅读