1

我正在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 令牌的正确方法吗?

4

1 回答 1

0

试试这个对我有用(swift 4 Code)

请求许可

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)")
}
于 2018-09-17T05:13:15.600 回答