Firebase(FCM)无法获取APNS令牌错误域= com.firebase.iid代码= 1001

时间:2016-08-12 03:59:20

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

我试图使用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 consol获得通知。但是,如果我们的服务器通过令牌向特定设备发送通知,我无法获得。

2 个答案:

答案 0 :(得分:4)

对我来说,我试着按照它来使它工作:

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

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

答案 1 :(得分:0)

听起来,您用来发送远程通知的服务器可能会记录您的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

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

相关问题