You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter集成Firebase推送时iOS端无法获取APNS令牌问题咨询

问题解答

核心结论

  • iOS模拟器无法获取真实有效的APNS令牌,必须使用物理iOS设备调试才能获取可用于Firebase推送的合法APNS令牌
  • 模拟器仅支持本地通知测试、通过本地.apns文件模拟推送送达效果,不支持与苹果APNS服务器通信,因此调用registerForRemoteNotifications后也不会触发令牌获取回调。

现有代码问题修正

你当前的AppDelegate.swift代码存在逻辑顺序错误:FirebaseApp.configure()需要放在注册推送相关逻辑之前,同时你需要补充Firebase Messaging的代理配置才能正确接收到APNS令牌回调,修正后代码如下:

import UIKit
import Flutter
import UserNotifications
import Firebase
import FirebaseMessaging

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate, MessagingDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    // 先初始化Firebase
    FirebaseApp.configure()
    // 设置Messaging代理
    Messaging.messaging().delegate = self
    
    if #available(iOS 10.0, *) {
           let center  = UNUserNotificationCenter.current()
           center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
               if error == nil{
                DispatchQueue.main.async {
                  UIApplication.shared.registerForRemoteNotifications()
                }
               }
           }
       }
       else {
           UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
           UIApplication.shared.registerForRemoteNotifications()
       }
    
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  // 实现APNS令牌获取回调
  override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken
    super.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
  }
  
  // 实现Firebase令牌获取回调
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
    print("获取到的FCM令牌: \(String(describing: fcmToken))")
  }
}

物理设备调试前置检查

切换到物理设备调试前,请确认完成以下配置:

  • 苹果开发者账号对应Bundle ID已开启Push Notifications能力
  • Xcode项目的Signing & Capabilities中已添加Push Notifications和Background Modes(Background Modes下勾选Remote notifications)
  • Firebase控制台已正确上传APNS认证密钥或推送证书

内容的提问来源于stack exchange,提问作者Wasiq Hussain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 10:00:01