如何使用Firebase检索FCM令牌?

时间:2018-09-17 04:04:50

标签: ios firebase apple-push-notifications firebase-cloud-messaging swift4

我正在使用Firebase尝试获取FCM令牌,以便可以在实际设备上测试Push通知。我得到了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令牌的正确方法吗?

1 个答案:

答案 0 :(得分:0)

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

请求许可

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

设置Firebase registerUserNotificationSettings

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)")
}