Firebase 推送通知无法获取 APNS 令牌错误 Domain=com.firebase.iid Code=1001 "(null)" using Swift3

Posted

技术标签:

【中文标题】Firebase 推送通知无法获取 APNS 令牌错误 Domain=com.firebase.iid Code=1001 "(null)" using Swift3【英文标题】:Firebase Push Notification Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)" using Swift3 【发布时间】:2017-01-09 12:09:24 【问题描述】:

我在关闭应用程序时收到(Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)" 错误(与 FCM 断开连接)。它出现在调试中,但是当应用程序正在运行并且我发送通知时,它只显示在调试中。谁能帮我解决这个问题?

 import UIKit
 import Firebase
 import UserNotifications
 import Firebase
 import FirebaseInstanceID
 import FirebaseMessaging


 @UIApplicationMain
 class AppDelegate: UIResponder, UIApplicationDelegate 

var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 

    // Register for remote notifications. This shows a permission dialog on first run, to
    // show the dialog at a more appropriate time move this registration accordingly.
    // [START register_for_notifications]
    if #available(ios 10.0, *) 
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: _, _ in )

        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        // For iOS 10 data message (sent via FCM)
        FIRMessaging.messaging().remoteMessageDelegate = self

     else 
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
    



    // [END register_for_notifications]
    FIRApp.configure()

    // Add observer for InstanceID token refresh callback.
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(self.tokenRefreshNotification),
                                           name: .firInstanceIDTokenRefresh,
                                           object: nil)

    return true


// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) 
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] 
        print("Message ID: \(messageID)")
    

    // Print full message.
    print(userInfo)


func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) 
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] 
        print("Message ID: \(messageID)")
    

    // Print full message.
    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)

// [END receive_message]
// [START refresh_token]
func tokenRefreshNotification(_ notification: Notification) 
    if let refreshedToken = FIRInstanceID.instanceID().token() 
        print("InstanceID token: \(refreshedToken)")
    

    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()

// [END refresh_token]
// [START connect_to_fcm]
func connectToFcm() 
    // Won't connect since there is no token
    guard FIRInstanceID.instanceID().token() != nil else 
        return;
    

    // Disconnect previous FCM connection if it exists.
    FIRMessaging.messaging().disconnect()

    FIRMessaging.messaging().connect  (error) in
        if error != nil 
            print("Unable to connect with FCM. \(error)")
         else 
            print("Connected to FCM.")
        
    

// [END connect_to_fcm]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) 
    print("Unable to register for remote notifications: \(error.localizedDescription)")


// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the InstanceID token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) 
    print("APNs token retrieved: \(deviceToken)")

    // With swizzling disabled you must set the APNs token here.
     //FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)


// [START connect_on_active]
func applicationDidBecomeActive(_ application: UIApplication) 
    connectToFcm()

// [END connect_on_active]
// [START disconnect_from_fcm]
func applicationDidEnterBackground(_ application: UIApplication) 
    FIRMessaging.messaging().disconnect()
    print("Disconnected from FCM.")

// [END disconnect_from_fcm]
 

 // [START ios_10_message_handling]
     @available(iOS 10, *)
   extension AppDelegate : UNUserNotificationCenterDelegate 

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 
    let userInfo = notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] 
        print("Message ID: \(messageID)")
    

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([])


func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) 
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] 
        print("Message ID: \(messageID)")
    

    // Print full message.
    print(userInfo)

    completionHandler()
  
  
  // [END ios_10_message_handling]
  // [START ios_10_data_message_handling]
  extension AppDelegate : FIRMessagingDelegate 
// Receive data message on iOS 10 devices while app is in the  foreground.
  func applicationReceivedRemoteMessage(_ remoteMessage:   FIRMessagingRemoteMessage) 
    print(remoteMessage.appData)
  
  

【问题讨论】:

注册APNS时是否调用error delegate? 调试中出现了这个错误(Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)")。 嗨。你看过这个post吗? 【参考方案1】:

1.如果您使用的是 Xcode 8.2 及更高版本。

在 Capabilities 中启用推送通知权利。请参考附件:

    请转到您的 Firebase 控制台,然后找到您的项目并转到其设置,在其中检查其云消息传递选项卡并将您的 .p12 证书上传到其中。

【讨论】:

感谢您的帮助,但我在问我的问题之前已经完成了所有操作,但仍然是同样的错误

以上是关于Firebase 推送通知无法获取 APNS 令牌错误 Domain=com.firebase.iid Code=1001 "(null)" using Swift3的主要内容,如果未能解决你的问题,请参考以下文章

Cordova 应用程序的 Firebase - 无法获取 APNS 令牌

APNS Firebase 通知未能获取令牌

如何检测真正的 iOS/APNS 推送令牌何时向 Firebase Cloud Messaging (FCM) 注册?

ios 应用更新后未收到 Firebase/APNS 通知

没有收到来自 Firebase 控制台的推送通知

APNS:无效令牌导致所有后续推送通知失败