Firebase(FCM)无法获取APNS令牌Error Domain = com.firebase.iid Code = 1001 [英] Firebase (FCM) Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001

查看:408
本文介绍了Firebase(FCM)无法获取APNS令牌Error Domain = com.firebase.iid Code = 1001的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用FCM进行通知。

但是< FIRInstanceID / WARNING> 无法获取 APNS 标记错误域= com.firebase.iid Code = 1001(null)发生,所以我不能得到通知。
有什么问题?

在控制台上,
无法获取 APNS token Error Domain = com.firebase.iid Code = 1001(null)



以下是我的代码 Appdelegate

 导入UIKit 
导入CoreData
导入Alamofire
导入Firebase
导入FirebaseInstanceID
导入FirebaseMessaging
$ b @UIApplicationMain $ b $ class AppDelegate:UIResponder,UIApplicationDelegate {

var window:UIWindow?

var badgeCount:Int = 0;

enum BasicValidity:String {
case成功=basicInfo
case失败=OauthAuthentificationError
}

func应用程序:UIApplication,didFinishLaunchingWithOptions launchOptions:[NSObject:AnyObject]?) - > Bool {
//在应用程序启动后替代自定义点。

$ b $ unsigned 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,如果令牌= FIRInstanceID.instanceID()。token(){
sendTokenToServer(令牌)
print(令牌是< \(令牌)对象:无)

。 > ;:)
}

return true
}

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

$ b $ print(didRegisterForRemoteNotificationsWithDeviceToken())

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

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

func application(application:UIApplication,didFailToRegisterForRemoteNotificationsWithError error:NSError){
$ b $ print(远程通知注册失败,错误:\(error.localizedDescription))
}

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

$ b $ print(didReceiveRemoteNotification())

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

处理程序(.NoData)

}

[开始refresh_token]
func tokenRefreshNotification(通知:NSNotification){
print(tokenRefreshNotification())
如果令牌= FIRInstanceID.instanceID ).token(){
print(InstanceID token:\(token))
sendTokenToServer(token)
FIRMessaging.messaging()。subscribeToTopic(/ topics / global)
print(订阅:/ topics / global)
}
connectToFcm()
}
// [END refresh_token]

$ func sendTokenToServer(currentToken:String){
print(sendTokenToServer()Token:\(currentToken))
//仅当需要时才将令牌发送给服务器如果必要
}

// [START connect_to_fcm]
func connectToFcm(){
FIRMessaging.messaging()。connectWithCompletion {(error)in
if error!= nil {
print (无法连接FCM。 \(error!))
} else {
print(Connected to FCM。)
}
}
}
// [ END connect_to_fcm]

func applicationWillResignActive(application:UIApplication){
//当应用程序即将从活动状态转移到非活动状态时发送,这可能发生在某些类型的临时中断(例如作为一个传入的电话或SMS消息),或者当用户退出应用程序,并开始过渡到后台状态
//使用此方法暂停正在进行的任务,禁用定时器,并降低OpenGL ES帧速率。
}
$ b $ [START disconnect_from_fcm]
func applicationDidEnterBackground(application:UIApplication){
//使用这个方法来暂停游戏方法释放共享资源,保存用户数据,使计时器无效,并存储足够的应用程序状态信息以恢复您的应用程序如果稍后终止,则返回到当前状态。
//如果您的应用程序支持后台执行,则调用此方法而不是applicationWillTerminate:当用户退出时。
$ b FIRMessaging.messaging()。disconnect()
print(与FCM断开连接)


func applicationWillEnterForeground(application:UIApplication) {
//作为从后台到非活动状态转换的一部分;在这里你可以撤消进入背景的许多变化。
}

func applicationDidBecomeActive(application:UIApplication){
//在应用程序处于非活动状态时,重新启动暂停(或尚未启动)的任务。如果应用程序以前位于后台,则可以选择刷新用户界面。
$ b $ UIApplication.sharedApplication()。applicationIconBadgeNumber = 0
connectToFcm()


$ b func applicationWillTerminate(application:UIApplication) {
//应用程序即将终止时调用。保存数据,如果适用。另请参阅applicationDidEnterBackground :.
//在应用程序终止之前,保存应用程序管理对象上下文中的更改。
self.saveContext()
}




  • 如果我使用包ID发送通知,我可以从Firebase CONSOL获取通知。但是我不能得到,如果我们的服务器发送通知到特定设备的令牌。
  • 对我来说,我尝试了以下thigs使其工作:
    $ b $ ul
  • 重新启用功能 - >推送通知,钥匙串共享和背景模式 - 远程通知

  • 重新安装应用程序(这将生成新的刷新令牌,后续运行将相同,因此可能无法在每次运行应用程序时都打印)。 $ b
  • 确保我已经在firebase控制台中上传了正确的.p12文件 - >项目设置 - >云消息传递

  • 在苹果开发人员中心重新检查配置文件激活ios开发人员配置配置文件。)



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


I'm trying to use FCM for notification.
But <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)" occurs so I can't get notification. What's the problem?

At the console,
Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"

and below is my code on 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 inactive 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()
    }

  • I can get notification from Firebase consol if I send notifications by using bundle ID. But I can't get if our server send notification to specific device with token.

解决方案

For me, I tried following thigs to make it work:

  • Re-Enabling Capabilities->push notification, keychain sharing and background modes->remote notification
  • Reinstalling the app(this will generate new refresh token, it will be same for subsequent runs so might not get printed every time you run the app).
  • Making sure that I have correct .p12 file uploaded in firebase console->project settings->cloud messaging
  • Rechecking provisioning profile in apple developer center(I had to re-activate ios developer provisioning profile.)

You might still get the warning but if you try to send notification from firebase console using the refresh token, it will work.

这篇关于Firebase(FCM)无法获取APNS令牌Error Domain = com.firebase.iid Code = 1001的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆