iOS 14 上的颤振 FCM 7 [英] Flutter FCM 7 on iOS 14

查看:21
本文介绍了iOS 14 上的颤振 FCM 7的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于在更新到 iOS14 后因 FCM 而疯狂的每个人Xcode12.我花了 2 天时间解决了这些问题.在模拟器上,它可以工作,但在真实设备上,它不会.也许这些说明可以帮助某人&防止浪费时间.另外,如果所有这些步骤都可以改进,那么听听 Flutter Guru 的一些想法会很棒:).

注意:

AppDelegate.swift

导入 UIKit导入颤振导入谷歌地图导入 Firebase导入 Firebase 消息传递@UIApplicationMain@objc 类 AppDelegate:FlutterAppDelegate {覆盖 func 应用程序(_ 应用程序:UIApplication,didFinishLaunchingWithOptions 启动选项:[UIApplication.LaunchOptionsKey:任何]?) ->布尔 {如果 #available(iOS 10.0, *) {UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate}GMSServices.provideAPIKey("")GeneratedPluginRegistrant.register(with: self)application.registerForRemoteNotifications()返回 super.application(应用程序,didFinishLaunchingWithOptions:launchOptions)}覆盖函数应用程序(_应用程序:UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken:数据){Auth.auth().setAPNSToken(deviceToken, 类型:.prod)}覆盖func应用程序(_应用程序:UIApplication,didReceiveRemoteNotification 通知:[AnyHashable : Any],fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) ->空白) {如果 Auth.auth().canHandleNotification(notification) {完成处理程序(.noData)返回}}覆盖func应用程序(_应用程序:UIApplication,打开url:URL,选项:[UIApplication.OpenURLOptionsKey:Any])->布尔 {如果 Auth.auth().canHandle(url) {返回真}返回假;}}

Info.plist

 <key>FirebaseAppDelegateProxyEnabled</key><假/><key>FirebaseScreenReportingEnabled</key><真的/>

消息示例(可调用函数)

您的消息必须使用以下选项发送:

<代码>{可变内容:真,内容可用:真,apnsPushType:背景"}

只是在可调用函数中使用的示例

exports.sendNotification = functions.https.onCall(异步(数据)=>{console.log(data, "this sendNotification data");var userTokens = [USERTOKEN1,USERTOKEN2,USERTOKEN3];变量有效载荷 = {通知: {标题: '',身体: '',图片: '',},数据: {类型:'',},};for (const [userToken,userUID] of Object.entries(userTokens)) {admin.messaging().sendToDevice(userToken, payload, {可变内容:真,内容可用:真,apnsPushType:背景"});}return {code: 100, message: "通知发送成功"};});

Flutter 消息服务

import 'dart:io';导入包:hive/hive.dart";导入'包:firebase_messaging/firebase_messaging.dart';导入'包:flutter_local_notifications/flutter_local_notifications.dart';导入包:octopoos/providers/app.dart";未来<动态>背景消息处理程序(地图<字符串,动态>消息)异步{}类 FirebaseMessagingService {最终 _app = AppProvider();var _prefs = Hive.box('preferences');FirebaseMessaging _firebaseMessaging = FirebaseMessaging();FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();无效初始化(){var android = AndroidInitializationSettings('mipmap/ic_launcher');var ios = IOSInitializationSettings();var platform = InitializationSettings(android, ios);_flutterLocalNotificationsPlugin.initialize(platform);_firebaseMessaging.configure(onLaunch:(地图<字符串,动态>消息)异步{_app.storeNotification(消息);},onResume: (Map<String, dynamic> 消息) async {_app.storeNotification(消息);},onMessage:(映射<字符串,动态>消息)异步{_app.storeNotification(消息);if (_prefs.get('pushServiceState') == true) _showNotification(message);},onBackgroundMessage:Platform.isIOS ?空:背景消息处理程序,);if (Platform.isIOS) iOSPermission();_firebaseMessaging.getToken().then((token) {_prefs.put('fcmToken', 令牌);});}无效 iOSPermission() {_firebaseMessaging.requestNotificationPermissions(IosNotificationSettings(声音:真,徽章:真,警报:真,临时:真));_firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings 设置) {print('IOS设置注册');});}未来<无效>_showNotification(地图<字符串,动态>消息)异步{var android = AndroidNotificationDetails('消息',八爪鱼",频道描述",);var iOS = IOSNotificationDetails();等待_flutterLocalNotificationsPlugin.show(0,消息['通知']['标题'],消息['通知']['正文'],NotificationDetails(安卓,iOS),);}}

调用小部件

final FirebaseMessagingService _fcm = FirebaseMessagingService();@覆盖无效 afterFirstLayout(BuildContext 上下文) {_fcm.initialise();}

只有经过所有这些步骤,我的 FCM 才能正常工作.

解决方案

如果可以的话,你可以试试 sample payload.

声明 这里

让有效载荷 = {通知: {标题:'匹配',body: `${user2name} 匹配你`,},数据: {键:'匹配',id:用户2,正文:用户名,click_action:FLUTTER_NOTIFICATION_CLICK";},安卓: {优先级:高",},apns:{有效载荷:{应用:{内容可用:真,},},标题:{apns-push-type":背景","apns-priority": "5",//当 `contentAvailable` 设置为 true 时,必须为 `5`."apns-topic": "io.flutter.plugins.firebase.messaging",//包标识符},},令牌:deviceTokenuUser1.data()['tokens'],};

For everyone who goes crazy from FCM after updating to iOS14 & Xcode12. I spent 2 days resolving the issues. On the simulator, it works but on a real device, it does not. Maybe these instructions can help someone & prevent wasting the time. Also, it would be great to listen to some thoughts from Flutter Guru if all these steps can be improved :).

Notice: Instructions for new FCM versions 9+

XCode Settings

AppDelegate.swift

import UIKit
import Flutter
import GoogleMaps
import Firebase
import FirebaseMessaging

@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
    }
    GMSServices.provideAPIKey("")
    GeneratedPluginRegistrant.register(with: self)
    application.registerForRemoteNotifications()
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

    override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Auth.auth().setAPNSToken(deviceToken, type: .prod)
    }

    override func application(_ application: UIApplication,
        didReceiveRemoteNotification notification: [AnyHashable : Any],
        fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        if Auth.auth().canHandleNotification(notification) {
          completionHandler(.noData)
          return
        }
    }

    override func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
        if Auth.auth().canHandle(url) {
          return true
        }
        return false;
      }
}

Info.plist

    <key>FirebaseAppDelegateProxyEnabled</key>
    <false/>
    <key>FirebaseScreenReportingEnabled</key>
    <true/>

Message Example (Callable function)

Your message must be sent with these options:

{
   mutableContent: true,
   contentAvailable: true,
   apnsPushType: "background"
}

Just an example to use in callable function

exports.sendNotification = functions.https.onCall(
    async (data) => {
        console.log(data, "this sendNotification data");
        var userTokens = [USERTOKEN1,USERTOKEN2,USERTOKEN3];
        var payload = {
            notification: {
                title: '',
                body: '',
                image: '',
            },
            data: {
                type:'',
            },
        };
        
        for (const [userToken,userUID] of Object.entries(userTokens)) {
            admin.messaging().sendToDevice(userToken, payload, {
                mutableContent: true,
                contentAvailable: true,
                apnsPushType: "background"
            });
        }
        
        return {code: 100, message: "notifications send successfully"};
    });

Flutter Message Service

import 'dart:io';
import 'package:hive/hive.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:octopoos/providers/app.dart';

Future<dynamic> backgroundMessageHandler(Map<String, dynamic> message) async {}

class FirebaseMessagingService {
  final _app = AppProvider();
  var _prefs = Hive.box('preferences');
  FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  void initialise() {
    var android = AndroidInitializationSettings('mipmap/ic_launcher');
    var ios = IOSInitializationSettings();
    var platform = InitializationSettings(android, ios);
    _flutterLocalNotificationsPlugin.initialize(platform);

    _firebaseMessaging.configure(
      onLaunch: (Map<String, dynamic> message) async {
        _app.storeNotification(message);
      },
      onResume: (Map<String, dynamic> message) async {
        _app.storeNotification(message);
      },
      onMessage: (Map<String, dynamic> message) async {
        _app.storeNotification(message);
        if (_prefs.get('pushServiceState') == true) _showNotification(message);
      },
      onBackgroundMessage: Platform.isIOS ? null : backgroundMessageHandler,
    );

    if (Platform.isIOS) iOSPermission();
    _firebaseMessaging.getToken().then((token) {
      _prefs.put('fcmToken', token);
    });
  }

  void iOSPermission() {
    _firebaseMessaging.requestNotificationPermissions(
        IosNotificationSettings(sound: true, badge: true, alert: true, provisional: true));
    _firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings settings) {
      print('IOS Setting Registed');
    });
  }

  Future<void> _showNotification(Map<String, dynamic> message) async {
    var android = AndroidNotificationDetails(
      'messages',
      "Octopoos",
      "channelDescription",
    );
    var iOS = IOSNotificationDetails();

    await _flutterLocalNotificationsPlugin.show(
      0,
      message['notification']['title'],
      message['notification']['body'],
      NotificationDetails(android, iOS),
    );
  }
}

Call on widget

final FirebaseMessagingService _fcm = FirebaseMessagingService();

  @override
  void afterFirstLayout(BuildContext context) {
    _fcm.initialise();
  }

Only after all these steps, my FCM work correctly.

解决方案

can u try sample payload if it works.

it is stated here

let payload = {
        notification: {
            title: 'Match',
            body: `${user2name} Match with You`,

        },
        data: {
            key: 'Match',
            id: user2,
            body: user2name,
            click_action: "FLUTTER_NOTIFICATION_CLICK"
        },
        android: {
            priority: "high",
        },
        apns: {
            payload: {
                aps: {
                    contentAvailable: true,
                },
            },
            headers: {
                "apns-push-type": "background",
                "apns-priority": "5", // Must be `5` when `contentAvailable` is set to true.
                "apns-topic": "io.flutter.plugins.firebase.messaging", // bundle identifier
            },
        },

        token: deviceTokenuUser1.data()['tokens'],
    };

这篇关于iOS 14 上的颤振 FCM 7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆