使用Firebase检索FCM令牌的方法?



我正在使用Firebase尝试获取FCM令牌,以便我可以在实际设备上测试推送通知。我得到APNS令牌很好,设置它

Messaging.messaging().apnsToken = deviceToken,

但是当我尝试使用Messaging.messaging().fcmToken来获取 FCM 令牌时,它返回 nil,以及

InstanceID.instanceID().instanceID { (result, error)  in } //returning nil.

但是,当我使用Messaging.messaging().retrieveFCMTokenInstanceID.instanceID().getID时,我得到了结果,但我看到没有人提倡使用这些函数来获取FCM令牌。这些函数是获取 FCM 令牌的正确方法吗?

试试这个它对我有用(swift 4 代码(

请求许可

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
self.setupFirebase(applicatin: application)
}

设置 FirebaseregisterUserNotificationSettings

func setupFirebase(applicatin:UIApplication)
{
if #available(iOS 10.0, *) {
let authOptions : UNAuthorizationOptions = [.alert, .badge , .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_,_ in })
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
// FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let notificationtype :UIUserNotificationType = [UIUserNotificationType.alert,UIUserNotificationType.badge,UIUserNotificationType.sound]
let notificationsettings = UIUserNotificationSettings(types: notificationtype, categories: nil)
applicatin.registerUserNotificationSettings(notificationsettings)
}
applicatin.registerForRemoteNotifications()
}

获取设备令牌

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
guard InstanceID.instanceID().token() != nil
else {
return
}
if let refreshedToken = InstanceID.instanceID().token()
{
print("InstanceID token: (refreshedToken)")
}
}

万一出现错误

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Filed to register : (error.localizedDescription)")
}

相关内容

  • 没有找到相关文章

最新更新