【问题标题】:FCM notifications delivering only with the app opened (iOS Flutter)FCM 通知仅在应用打开时提供(iOS Flutter)
【发布时间】:2021-04-17 07:32:50
【问题描述】:

在这个项目中,如果一个给定的用户做某事,其他用户会收到来自 Firebase Messaging 的推送。在 android 中它工作正常,但在 iOS 中,只有在打开应用程序时,消息才会到达用户手机。如果在后台,当您再次应用该应用时,它会显示通知

我已经做过的事情:

  • 1 在developers.apple 中创建一个密钥并在firebase 中应用它
  • 2 使用 googleservices.plist 提供我的项目
  • 3 打开推送通知和后台模式,并在后台模式下启用后台获取和远程通知。
  • 4 在我的 info.plist 中添加了此代码:
<key>FirebaseScreenReportingEnabled</key>
<true/>
<key>FirebaseAppDelegateProxyEnabled</key>
<true/>

在 AppDelegate.swift 中,我已经尝试了这两个代码: 1(来自 FirebaseMessaging 文档)

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
    }
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

和2

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)
  }
}


第二个在应用打开的情况下到达消息,第一个根本没有到达。 我正在使用 FlutterLocalNotifications 来处理应用何时打开,可能是 LocalNotifications 和 FCM 之间的一些冲突(我不确定,只是想)。

我该如何处理才能接收后台通知?:

有什么我想念的吗?以下代码是我的 PushNotifications.dart

import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:app_md/providers/auth_provider.dart';
import 'package:app_md/providers/notification_plugin.dart';
import 'package:app_md/utils/app_routes.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;

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: 's',
            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,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");

       // _navigateToItemDetail(message);
      },
      // Called when the app is in the background and its opened from the notif
      onResume: (Map<String, dynamic> message) async {
        print("onMessage: ${message}");
      },
    );

  }

  subscribeToTopicNotification() async {
    await _firebaseMessaging.subscribeToTopic("MYTOPIC");
  }

  unsubscribeToTopicNotification() async {
    await _firebaseMessaging.unsubscribeFromTopic("MYTOPIC");
  }

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

    print(response.body);
  }
}

【问题讨论】:

    标签: ios swift firebase flutter firebase-cloud-messaging


    【解决方案1】:

    您正在发送数据消息而不是通知消息。您描述的行为(重新打开应用程序时发送通知)是数据消息的行为。更多信息请关注docs

    【讨论】:

    • 我从 http 请求中删除了“数据”,但仍然面临问题。这很奇怪,因为在 Android 中一切正常,而 iOS 则不行
    • 在 Android 中,onMessage() 会被触发,即使应用程序在后台,但在 IOS 上它不会触发。所以请重新检查它,因为如果它是一条数据消息,这种行为是预期的。您使用的是哪个版本的 firebase?
    • firebase_storage: ^5.1.0 firebase_core: ^0.5.3 cloud_firestore: ^0.14.4 firebase_messaging: ^7.0.3 firebase_analytics: ^6.3.0
    • 嗯,这很奇怪,尝试使用 8.0 开发版,如果这是 firebase 的问题,现在肯定会修复,因为这是一个非常严重的问题。但我仍然认为问题是我上面描述的问题。
    • 你说的有道理,但是看我的帖子正文:'{"notification": {"body": "${body}", "title": "${title}", "content_available": "true"}, "priority": "high", "to": "/TOPIC"}';这里没有引用数据,为什么将其归因于数据消息?
    猜你喜欢
    • 2020-11-25
    • 1970-01-01
    • 2021-01-21
    • 2016-09-29
    • 2019-06-15
    • 2021-06-25
    • 2021-11-07
    • 1970-01-01
    • 2020-02-11
    相关资源
    最近更新 更多