【发布时间】:2017-09-17 23:18:06
【问题描述】:
我在我的应用中使用 Firebase 通知。当我第一次安装我的应用程序时,FIRInstanceID.instanceID().token() 返回 nil,但下次它不会返回 nil。除了这个,一切都做得很完美。
代码如下:
import UIKit
import Firebase
import FirebaseMessaging
import FirebaseInstanceID
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate
{
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
//Configuring Firebase
FIRApp.configure()
if #available(iOS 10.0, *)
{
print("Test")
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in
if granted
{
//self.registerCategory()
}
}
// 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()
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)
}
func tokenRefreshNotification(notification: NSNotification)
{
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()
}
func connectToFcm()
{
FIRMessaging.messaging().connect { (error) in
if (error != nil)
{
print("Unable to connect with FCM. \(error)")
}
else
{
print("Connected to FCM.")
}
}
}
}
在远程页面中我正在调用 Firebase InstanceID 令牌
let token = FIRInstanceID.instanceID().token()
但第一次它返回 nil 值。
【问题讨论】:
-
你能展示一些你尝试过的代码吗!
-
在 cmets 中有类似问题的答案:stackoverflow.com/q/40859930/4815718
-
@BobSnyder 如何为密钥 firInstanceIDTokenRefresh 添加观察者以检索最新的令牌
-
其他人必须回答。我不知道。
-
你是使用APNS和FCM还是只使用FCM
标签: ios firebase swift3 instanceid