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

Flutter在真实iOS设备上调用getAPNSToken()返回null求助

排查iOS真机无法获取APNS Token的问题

以下是针对你的问题的具体排查和修复步骤:

1. 通知权限未正确请求

iOS真机需要用户明确授权通知权限才能注册远程推送,模拟器会默认授权,但真机不会。你的代码中缺少权限请求逻辑,导致registerForRemoteNotifications可能因权限不足而失败。

修复Flutter代码:

在调用getAPNSToken()前先请求并确认通知权限:

if (Platform.isIOS) {
  // 请求通知权限
  NotificationSettings settings = await FirebaseMessaging.instance.requestPermission(
    alert: true,
    badge: true,
    sound: true,
  );
  
  if (settings.authorizationStatus == AuthorizationStatus.authorized) {
    String? apnsToken = await FirebaseMessaging.instance.getAPNSToken();
    if (value == true) {
      print("The token is ........${apnsToken}");
    }
  } else {
    print("用户未授予通知权限,无法获取APNS Token");
  }
}

修复AppDelegate.swift:

将原有的application.registerForRemoteNotifications()移到权限请求成功后执行,并修正代理声明:

// 让AppDelegate遵守UNUserNotificationCenterDelegate协议
@objc class AppDelegate: FlutterAppDelegate, UNUserNotificationCenterDelegate {
  
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    FirebaseApp.configure()
    GMSServices.provideAPIKey("XXXXXXXXXXXXXXXX")
    GeneratedPluginRegistrant.register(with: self)
    
    // 配置通知代理并请求权限
    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
      if granted {
        DispatchQueue.main.async {
          application.registerForRemoteNotifications()
        }
      }
    }
    
    if(!UserDefaults.standard.bool(forKey: "Notification")) {
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UserDefaults.standard.set(true, forKey: "Notification")
    }
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
  // 其余原有方法保持不变
}

2. 代理声明错误

原代码中UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate使用可选转换,且AppDelegate未声明遵守该协议,导致代理设置失败,无法正确处理通知回调。修复后直接让AppDelegate继承协议,并直接赋值代理。

3. 检查Xcode推送配置

  • 打开Xcode项目,进入Signing & Capabilities,确认已开启Push Notifications权限。
  • 确认Apple开发者账号已配置正确的APNs证书(开发、生产环境需分别配置)。
  • 检查GoogleService-Info.plist是Firebase控制台下载的最新版本,确保文件中BUNDLE_ID与项目包名完全一致。

4. 验证回调触发情况

运行真机后查看Xcode控制台:

  • 如果未打印Token: \(deviceToken),说明didRegisterForRemoteNotificationsWithDeviceToken未触发,大概率是权限未授权或证书配置错误。
  • 如果已打印Token但Flutter端getAPNSToken()返回null,可在Messaging.messaging().apnsToken = deviceToken后添加print("Firebase APNs Token set: \(Messaging.messaging().apnsToken)"),验证Firebase是否正确接收了设备Token。

内容的提问来源于stack exchange,提问作者EBENEZER OCANSEY

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:03:12