【问题标题】:I cannot receive notifications from Firebase Messaging with the app in background我无法在后台收到来自 Firebase Messaging 的通知
【发布时间】:2021-04-23 06:46:30
【问题描述】:

在我的 Flutter 应用中,管理员用户可以通过 FCM 向其他用户发送通知。在 android 中已经可以工作,但在 iOS 中,通知仅在应用程序打开时到达。我已经在互联网上尝试了很多东西,但仍然无法正常工作。

这是管理推送的 dart 代码:

Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
  if (message.containsKey('data')) {
    // Handle data message
    final dynamic data = message['data'];
  }

  if (message.containsKey('notification')) {
    // Handle notification message
    final dynamic notification = message['notification'];
  }

  // Or do other work.
}


class PushNotificationsManager {

  PushNotificationsManager._();

  factory PushNotificationsManager() => _instance;

  static final PushNotificationsManager _instance = PushNotificationsManager
      ._();

  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  final NotificationPlugin _notificationPlugin = NotificationPlugin();

  Future<void> init() async {
    if (Platform.isIOS) {
      _firebaseMessaging.requestNotificationPermissions(
          IosNotificationSettings());
    }
    _firebaseMessaging.configure(
      // Called when the app is in the foreground and we receive a push notif.
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: ${message}");
        print(message['notification']['body']);
        _notificationPlugin.showNotification(
            title: 'TEST',
            content: message['notification']['body']
        );
        //sendNotification();
      },
      // Called when the app has been closed completely and its opened
      // from the notification directly

      //onBackgroundMessage: Platform.isAndroid ? myBackgroundMessageHandler:null,
      onBackgroundMessage: myBackgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
        if(Platform.isIOS){
          message = _modifyNotificationJson(message);
        }
      },
      // Called when the app is in the background and its opened from the notif
      onResume: (Map<String, dynamic> message) async {
        print("onMessage: ${message}");
        if(Platform.isIOS){
          message = _modifyNotificationJson(message);
        }
      },
    );

  }

  Map _modifyNotificationJson(Map<String, dynamic> message) {
    message['data'] = Map.from(message ?? {});
    message['notification'] = message['aps']['alert'];
    return message;
  }


  Future sendNotification(String body, String title) async {
    final String url = 'https://fcm.googleapis.com/fcm/send';
    var notification;
    notification =
    '{"notification": {"body": "${body}", "title": "${title}", "content_available": "true", "click_action": "FLUTTER_NOTIFICATION_CLICK"}, "priority": "high", "to": "MYTOPIC"}';
    final response = await http.post(
        url,
        headers: <String, String>{
          "Content-Type": "application/json",
          "Keep-Alive": "timeout=5",
          "Authorization": "key=MYKEY"
        },
        body: notification
    );

    print(response.body);
  }
}

AppDelegate.swift:

import UIKit
import Flutter
import Firebase

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    if #available(iOS 10.0, *) {
      // For iOS 10 display notification (sent via APNS)
      UNUserNotificationCenter.current().delegate = self

      let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
      UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_, _ in })
    } else {
      let settings: UIUserNotificationSettings =
      UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
      application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()
    FirebaseApp.configure()
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}


我已经在 xcode 中启用了 pushNotifications 和后台模式,已经检查了我的证书,但问题仍然存在。有人可以帮助我吗?我花了一个多星期的时间。我做的对吗?

【问题讨论】:

    标签: ios swift firebase google-cloud-functions


    【解决方案1】:

    根据Pushing Background Updates to Your App提及的文档检查以下几点

    1.

    要发送后台通知,请使用以下命令创建远程通知 仅包含内容可用键的 aps 字典,如 如清单 1 所示。您可以在有效负载中包含自定义键,但是 aps 字典不能包含任何会触发用户的键 互动。

    此外,通知的 POST 请求应包含 apns-push-type 标头字段,其值为 background,以及 apns-priority 字段,值为 5。

    • 如果有东西强制退出或杀死应用程序,系统会丢弃 举行通知。如果用户启动应用程序,系统 立即发送保留的通知。
    • 提供背景 通知,系统会在后台唤醒您的应用。
    1. (我在你appDelegate的代码中看不到didReceiveRemoteNotification)

    在 iOS 上,它会调用您的应用代理 application(_:didReceiveRemoteNotification:fetchCompletionHandler:) 方法。

    另外Sending Notification Requests to APNs 声明:

    5.

    使用后台推送类型来传递内容的通知 背景,并且不触发任何用户交互。如果你设置 这种推送类型,apns-topic 标头字段必须使用您应用的捆绑包 ID作为主题。始终使用优先级 5。使用优先级 10 是错误的。

    如果满足上述清单,它应该可以工作。您可以提供您正在发送的通知的最终内容,或者您​​在应用运行时在通知中收到的有效负载。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 2020-12-12
      相关资源
      最近更新 更多