集成Firebase SDK后iOS推送通知失效,didRegister方法未触发
解决Firebase集成后APNS
didRegisterForRemoteNotificationsWithDeviceToken不调用的问题 我之前也踩过一模一样的坑!Firebase Messaging默认会接管APNS的部分注册逻辑,导致咱们自己的回调方法被“屏蔽”了,不过只要调整几个配置和代码顺序就能解决,亲测有效:
1. 关闭Firebase的自动代理
首先在你的Info.plist里添加一个布尔值键FirebaseAppDelegateProxyEnabled,把它设为NO。这一步是告诉Firebase不要自动接管AppDelegate的推送相关代理方法,让咱们自己来处理。
2. 调整代码顺序与添加Firebase Messaging代理
你需要先初始化Firebase,再注册推送通知,同时要设置Messaging的代理并实现对应的方法,确保APNS的deviceToken能同步给Firebase。修改后的代码如下:
import FirebaseMessaging @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 先初始化Firebase FirebaseApp.configure() // 设置Messaging代理 Messaging.messaging().delegate = self // 注册推送通知 registerForPushNotifications() return true } func registerForPushNotifications() { UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in print("Permission granted: \(granted)") guard granted else { return } // 授权成功后一定要调用这行,触发远程通知注册 DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // 打印咱们自己需要的token let tokenParts = deviceToken.map { data -> String in return String(format: "%02.2hhx", data) } let token = tokenParts.joined() print("Device Token: \(token)") // 把token传给Firebase Messaging Messaging.messaging().apnsToken = deviceToken } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Failed to register: \(error)") } // 实现Messaging的代理方法,获取Firebase的推送token func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) { print("Firebase FCM Token: \(fcmToken ?? "nil")") // 这里可以把FCM token上传到你的服务器 } }
3. 关键注意点
- 初始化顺序:必须先调用
FirebaseApp.configure(),再去注册推送,否则Firebase无法正确绑定APNS的token。 - 授权后的注册:在
requestAuthorization的闭包里,授权成功后一定要调用UIApplication.shared.registerForRemoteNotifications(),这是触发didRegisterForRemoteNotificationsWithDeviceToken的关键步骤(你原来的代码里漏掉了这一步,可能之前没Firebase的时候隐式调用了,但结合Firebase必须显式添加)。 - 代理设置:要确保
UNUserNotificationCenter.current().delegate = self和Messaging.messaging().delegate = self都设置好,不然相关回调不会触发。
这样调整之后,你的didRegisterForRemoteNotificationsWithDeviceToken就能正常被调用,同时Firebase Messaging也能正常工作啦!
内容的提问来源于stack exchange,提问作者DiegoQ
相关产品推荐
相关产品推荐

