Flutter Firebase手机认证真机失效求助:模拟器正常,真机提示Invalid token错误
解决Flutter Firebase Phone Auth在iOS真机上失效的问题
看起来你遇到的核心问题是Invalid token错误,结合控制台的400 HTTP状态码,这说明Firebase没有收到有效的APN设备令牌,导致手机号验证流程失败。模拟器能正常工作是因为它不需要真实的APN令牌,Firebase会用测试通道处理,而真机必须依赖正确的APN配置和令牌传递。下面是一步步的解决方案:
1. 补全AppDelegate的APN令牌处理逻辑
你的AppDelegate.swift里缺少了关键的APN令牌获取和传递给Firebase的代码,这是导致Invalid token的主要原因。修改后的代码如下:
import UIKit import Flutter import Firebase import FirebaseMessaging @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { FirebaseApp.configure() // 请求推送权限,真机必须用户允许才能获取令牌 UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in if granted { DispatchQueue.main.async { application.registerForRemoteNotifications() } } } GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } // 接收APN令牌并传递给Firebase Messaging override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Messaging.messaging().apnsToken = deviceToken super.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) } // 处理推送通知(可选,但建议添加) override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { Messaging.messaging().appDidReceiveMessage(userInfo) completionHandler(.newData) } }
2. 确认APN密钥和Firebase配置的一致性
- 检查你在Firebase后台添加的APN密钥:确保密钥的Team ID和你Xcode项目里的Team ID完全一致,密钥没有过期,并且是对应环境创建的(测试真机用开发环境密钥,正式发布用生产环境密钥)。
- 确认Firebase控制台里的iOS应用Bundle ID和你Xcode项目中的
PRODUCT_BUNDLE_IDENTIFIER完全匹配(大小写敏感)。 - 确保
GoogleService-Info.plist已经正确添加到Xcode项目中,并且没有重复文件。
3. 检查Xcode项目的Capabilities配置
- 确认
Signing & Capabilities中已经开启Push Notifications。 - 确认
Background Modes里的Remote notifications已经勾选(你提到已经勾选,但再次确认没有误操作取消)。
4. 依赖和版本检查
- 确保你的
pubspec.yaml中已经添加了firebase_messaging依赖,并且版本和firebase_auth兼容:
dependencies: flutter: sdk: flutter firebase_auth: ^x.x.x firebase_messaging: ^x.x.x
- 运行
flutter pub get更新依赖,然后重新编译项目到真机。
5. 真机测试注意事项
- 测试的真机必须登录有效的Apple ID,并且在首次打开应用时允许推送权限。
- 如果之前拒绝过推送权限,可以在
设置 > 你的应用 > 通知里重新开启。 - 确保真机网络正常,能访问Google API(如果有网络限制,可能需要检查防火墙或代理)。
完成以上步骤后,重新打包安装到真机,应该就能正常触发Phone Auth的验证流程了。
内容的提问来源于stack exchange,提问作者user3903484
相关产品推荐
相关产品推荐

