【问题标题】:Firebase (FCM) Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001Firebase (FCM) 无法获取 APNS 令牌错误域 = com.firebase.iid 代码 = 1001
【发布时间】:2016-12-18 23:28:45
【问题描述】:

我正在尝试使用 FCM 进行通知。
但是<FIRInstanceID/WARNING> 无法获取APNS 令牌错误Domain=com.firebase.iid Code=1001 "(null)" 发生所以我无法收到通知。 有什么问题?

在控制台,
获取APNS令牌Error Domain=com.firebase.iid Code=1001 "(null)"失败

下面是我在Appdelegate上的代码

import UIKit
import CoreData
import Alamofire
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var badgeCount : Int = 0;

    enum BasicValidity : String {
        case Success = "basicInfo"
        case Fail = "OauthAuthentificationError"
    }

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.


        let uns: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(uns)
        application.registerForRemoteNotifications()

        FIRApp.configure()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)

        if let token = FIRInstanceID.instanceID().token() {
            sendTokenToServer(token)
            print("token is < \(token) >:")
        }

        return true
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){


        print("didRegisterForRemoteNotificationsWithDeviceToken()")

        // if FirebaseAppDelegateProxyEnabled === NO:
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .Sandbox)

        print("APNS: <\(deviceToken)>")
    }

    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError){

         print("Registration for remote notification failed with error: \(error.localizedDescription)")
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){


        print("didReceiveRemoteNotification()")

        //if FirebaseAppDelegateProxyEnabled === NO:
        FIRMessaging.messaging().appDidReceiveMessage(userInfo)

       // handler(.NoData)

    }

    // [START refresh_token]
    func tokenRefreshNotification(notification: NSNotification) {
        print("tokenRefreshNotification()")
        if let token = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(token)")
            sendTokenToServer(token)
            FIRMessaging.messaging().subscribeToTopic("/topics/global")
            print("Subscribed to: /topics/global")
        }
        connectToFcm()
    }
    // [END refresh_token]

    func sendTokenToServer(currentToken: String) {
        print("sendTokenToServer() Token: \(currentToken)")
        // Send token to server ONLY IF NECESSARY
    }

    // [START connect_to_fcm]
    func connectToFcm() {
        FIRMessaging.messaging().connectWithCompletion { (error) in
            if error != nil {
                print("Unable to connect with FCM. \(error!)")
            } else {
                print("Connected to FCM.")
            }
        }
    }
    // [END connect_to_fcm]

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    // [START disconnect_from_fcm]
    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

       // UIApplication.sharedApplication().applicationIconBadgeNumber = 0
         connectToFcm()

    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }
  • 如果我使用捆绑包 ID 发送通知,我可以从 Firebase 控制台获得通知。但是如果我们的服务器使用令牌向特定设备发送通知,我无法获得。

【问题讨论】:

  • @Frank van Puffelen 你能帮帮我吗?
  • 鉴于您在从控制台发送到应用程序(捆绑 id)时收到通知,这意味着您的应用程序具有有效的 IID 令牌,但我不确定您是用于发送到。如果您卸载该应用程序并重新安装它,您可能会注意到打印了几个令牌,只有最后一个有效。我也会尝试发送到您正在使用的主题,因为这也将确认设备具有有效的令牌,但您可能使用了错误的令牌。
  • @kimpro 我遇到了同样的问题 - 你能找到解决方法吗?谢谢!

标签: ios swift firebase firebase-cloud-messaging firebase-notifications


【解决方案1】:

对我来说,我尝试了以下方法以使其发挥作用:

  • 重新启用功能->推送通知、钥匙串共享和后台模式->远程通知
  • 重新安装应用程序(这将生成新的刷新令牌,后续运行时相同,因此可能不会在每次运行应用程序时打印)。
  • 确保我在 firebase 控制台->项目设置->云消息传递中上传了正确的 .p12 文件
  • 在苹果开发者中心重新检查配置文件(我不得不重新激活 ios 开发者配置文件。)

您可能仍会收到警告,但如果您尝试使用刷新令牌从 Firebase 控制台发送通知,它将起作用。

【讨论】:

  • 在哪里可以找到刷新令牌。tokenRefreshNotification 没有被调用
  • @KrutarthPatel 不确定您的问题,但如果您的 tokenRefreshNotification 未被调用,您可能需要卸载并重新安装该应用程序。如果您将调试点放在该函数中,则在配置 firebase 后将调用它。
  • 我收到警告并能够使用 firebase 控制台发送消息,但由于某些问题,我的应用程序无法启动。该怎么办。
【解决方案2】:

听起来您用来传递远程通知的服务器可能有您的 FCM 令牌的旧记录。 Google FCM 文档声明 FCM 令牌可以在以下情况下轮换(更改):

  • 应用已在新设备上恢复
  • 用户卸载/重新安装应用程序
  • 用户清除应用数据。

他们引用了使用委托回调方法更新服务器的此令牌记录的良好做法:

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    // Send the token to your server here
}

该方法对我不起作用,因此我必须在每次应用启动时手动更新它(延迟大约 20-25 秒后,因为轮换并不总是即时的)。你可以这样做:

let token = Messaging.messaging().fcmToken  // Send this to your server

在这些更改之后,我仍然会收到警告控制台日志消息,但推送通知每次都能正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 2017-01-02
    相关资源
    最近更新 更多