FIRInstanceID 在 FIRInstanceIDAPNSTokenType.Sandbox 中变为零
Posted
技术标签:
【中文标题】FIRInstanceID 在 FIRInstanceIDAPNSTokenType.Sandbox 中变为零【英文标题】:FIRInstanceID getting nil in FIRInstanceIDAPNSTokenType.Sandbox 【发布时间】:2016-07-29 07:14:31 【问题描述】:您好,我正在使用第一次 FCM 推送通知,我已经使用以下代码实现了 FCM:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
FIRApp.configure()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification),
name: kFIRInstanceIDTokenRefreshNotification, object: nil)
func tokenRefreshNotification(notification: NSNotification)
print("refresh token call")
let refreshedToken = FIRInstanceID.instanceID().token()!
print("InstanceID token: \(refreshedToken)")
NSUserDefaults.standardUserDefaults().setObject(refreshedToken, forKey: "deviceToken");
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
updateDeviceToken()
func connectToFcm()
FIRMessaging.messaging().connectWithCompletion (error) in
if (error != nil)
print("Unable to connect with FCM. \(error)")
else
print("Connected to FCM.")
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
/*when I comment above line app works fine but not receiving notificaiton
in background and If i uncomment above line than app crashes
for the first time when I launch on device */
func applicationDidBecomeActive(application: UIApplication)
connectToFcm()
控制台日志在应用崩溃前打印<FIRInstanceID/WARNING> APNS Environment in profile: development
。
现在的问题是,当我设置 FIRInstanceIDAPNSTokenType.Sandbox
时,应用程序在我第一次启动 bcaz 时崩溃,我在 tokenRefreshNotification
方法中得到 FIRInstanceID.instanceID().token()!
nil。
如果我没有将任何 APNS 令牌设置为FIRInstanceID
,那么应用程序可以正常工作,但在这种情况下我没有收到后台通知。并给我解决如何检查FIRInstanceID.instanceID().token()!
是否为零
【问题讨论】:
有时你会在tokenRefreshNoification中得到nil,如果最初生成的token很快被新的token替换,就会出现这种情况。您应该使用另一个非零令牌获得另一个对 tokenRefreshNotification 的回调。 【参考方案1】:我刚刚在tokenRefreshNotification
方法中解决了我的崩溃处理问题。我正在使用此代码检查 TokenId 是否为零,现在我的应用程序没有崩溃,而且我正在获取令牌 ID:
func tokenRefreshNotification(notification: NSNotification)
// print("refresh token call")
guard let contents = FIRInstanceID.instanceID().token()
else
return
// let refreshedToken = FIRInstanceID.instanceID().token()!
print("InstanceID token: \(contents)")
NSUserDefaults.standardUserDefaults().setObject(contents, forKey: "deviceToken");
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
updateDeviceToken()
【讨论】:
以上是关于FIRInstanceID 在 FIRInstanceIDAPNSTokenType.Sandbox 中变为零的主要内容,如果未能解决你的问题,请参考以下文章