Flutter FCM iOS 问题 - 在检索 FCM 令牌之前未设置 APNS 设备令牌

问题描述 投票:0回答:4

我在 Flutter 应用程序中使用 firebase_messaging v9.0.1。在基于 https://pub.dev/packages/firebase_messaging/example 配置此库时,我能够在前台和后台状态下接收 Android 的通知。但同样的方法对于 iOS 来说是行不通的。我收到以下错误,

在检索发件人 ID '' 的 FCM 令牌之前未设置 APNS 设备令牌。对此 FCM 令牌的通知将不会通过 APNS 传递。设置 APNS 设备令牌后,请务必重新检索 FCM 令牌。

我的 iOS 设备已连接到互联网,并且运行时没有出现与网络相关的问题。

除了适用于 iOS 的 FirebaseMessaging.instance.getToken() 之外,我还想调用任何其他函数吗? 请帮忙。

谢谢。

ios flutter firebase-cloud-messaging apple-push-notifications
4个回答
13
投票

我遇到了同样的问题,我再次一步步查看 Firebase 文档,并意识到调试和发布模式下缺少推送通知功能。

解决问题的步骤:

  1. 转到xcode
  2. 选择跑步者
  3. 签名和功能
  4. 检查调试和发布功能,您需要有后台模式和推送通知

push notification capability

https://firebase.flutter.dev/docs/messaging/apple-integration


2
投票

尝试在真实设备上运行

试试这个:

AppDelegate.swift

import UIKit
import Flutter
import Firebase
import FirebaseMessaging
import UserNotifications
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    var firebaseToken : String = "";
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    Messaging.messaging().delegate = self;
    FirebaseApp.configure()
    GeneratedPluginRegistrant.register(with: self)
    Messaging.messaging().isAutoInitEnabled = true;
    self.registerForFirebaseNotification(application: application);
    return true;
   // GeneratedPluginRegistrant.register(with: self)
    
  }
   override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken : Data){
    print("X__APNS: \(String(describing: deviceToken))")
       Messaging.messaging().apnsToken = deviceToken;
    //Messaging.messaging().setAPNSToken(deviceToken, type:MessagingAPNSTokenType.prod )
    }
    
    override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("X_ERR",error);
    }
    
     func registerForFirebaseNotification(application : UIApplication){
    //    Messaging.messaging().delegate     = self;
        if #available(iOS 10.0, *) {
            //UNUserNotificationCenter.current().delegate = self ;
            let authOpt : UNAuthorizationOptions = [.alert, .badge, .sound];
            UNUserNotificationCenter.current().requestAuthorization(options: authOpt, completionHandler: {_, _ in})
            UNUserNotificationCenter.current().delegate = self ;
        }else{
            let settings : UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)                
            application.registerUserNotificationSettings(settings);
        }
        application.registerForRemoteNotifications();
    }
}

extension AppDelegate : MessagingDelegate{
    func messaging(_messagin : Messaging, didRecieveRegistrationToken fcmToken : String){
        self.firebaseToken = fcmToken;
        print("X__FCM: \(String(describing: fcmToken))")
    }
    func messaging(_messagin : Messaging, didRecieve remoteMessage : Any){
        //self.firebaseToken = fcmToken;
        print("REMOTE__MSG: \(remoteMessage)")
    }
    func application(_ application : UIApplication,didRecieveRemoteNotification uinfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void){
        print("WITH__APN: \(uinfo)")
    }
}

podfile

target 'Runner' do
  use_frameworks!
  use_modular_headers!

#  pod 'FirebaseFirestore', :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git', :tag => '7.11.0'

  pod 'Firebase/Auth'
  pod 'Firebase/Analytics'
  pod 'FBSDKLoginKit'
  pod 'Firebase/Messaging'

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

pubspec.yaml

  cloud_firestore: ^2.0.0
  firebase_auth: ^1.1.2
  firebase_core: ^1.1.0
  firebase_messaging: ^9.1.3
  flutter_local_notifications: ^5.0.0+3

也回答了这里


1
投票

我解决这个问题的方法是,我不是通过调试模式运行应用程序,而是存档应用程序并通过临时下载它,这以某种方式解决了问题


0
投票

我也收到了此错误,但就我而言,我在 Firebase 中设置了 APN 证书而不是 APN 密钥。我必须更新 Firebase 中已过期的 APN 证书。这解决了错误,我可以在我的应用程序中使用 .getToken() 获取令牌。

更新:在 Firebase > 项目设置 > 云消息传递中,我为我的 flutter iOS 应用程序上传了 APNs 身份验证密钥。我没有上传任何 APNs 证书。请按照此处的指南了解如何创建和上传 APN 身份验证密钥:https://firebase.flutter.dev/docs/messaging/apple-integration/

然后在我的 flutter 项目中我用它来获取 FCM 令牌

import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';


Future<String?> getFirebaseToken() async {
  String? fcmToken;
  if (Platform.isIOS) {
    // On iOS we need to see an APN token is available first
    String? apnsToken = await FirebaseMessaging.instance.getAPNSToken();
    if (apnsToken != null) {
      fcmToken = await FirebaseMessaging.instance.getToken();
    }
    else {
      // add a delay and retry getting APN token
      await Future<void>.delayed(const Duration(seconds: 3,));
      apnsToken = await FirebaseMessaging.instance.getAPNSToken();
      if (apnsToken != null) {
        fcmToken = await FirebaseMessaging.instance.getToken();
      }
    }
  }
  else {
    // android platform
    fcmToken = await FirebaseMessaging.instance.getToken();
  }
  return fcmToken;
}

在我的 main.dart 中,我像这样初始化 firebase

  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  FirebaseMessaging.instance.onTokenRefresh.listen((String token) {
    String? fcmToken = await getFirebaseToken();
    // save token to storage or server-side depending where you want 
    // to send push notification
  })
© www.soinside.com 2019 - 2024. All rights reserved.