Swift 4, Firebase 5.8.0 FCM токен ноль - PullRequest
       6

Swift 4, Firebase 5.8.0 FCM токен ноль

0 голосов
/ 15 сентября 2018

Я настраиваю push-уведомления, и все идет хорошо, пока я не попытаюсь получить токен FCM, чтобы я мог отправить тестовое сообщение на реальное устройство.Используя модули Firebase 5.8.0, FirebaseCore (5.1.3), FirebaseInstanceID (3.2.1) и FirebaseMessaging (3.1.2), я могу нормально получить токен APNS, но каждый раз, когда я пытаюсь получить токен FCM, он приходиткак nil или когда я использую InstanceID.instanceID (). instanceID (handler :), это приводит к некоторому тайм-ауту с кодом ошибки 1003 и результату nil.didReceiveRegistrationToken также не вызывается.Я перепробовал много решений 2017 года, но они либо устарели, либо не работают.MessageDelegate и UNUserNotificationCenterDelegate установлены, push-уведомления и совместное использование цепочки для ключей включены в возможности, метод swizzling отключен через p-list, и вот моя функция didRegisterForRemoteNotificationsWithDeviceToken, где я правильно получаю токен apns.Есть идеи?Спасибо.

`public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("Registration Successful: Device token \(deviceToken)")
    Messaging.messaging().apnsToken = deviceToken
    print("Messaging APNS Token:\(Messaging.messaging().apnsToken)")
    print("Instance Id: \(InstanceID.instanceID().token())") //deprecated & returns nil

    print("Messaging APNS Token:\(Messaging.messaging().apnsToken)")
    print("Token:\(Messaging.messaging().fcmToken)") // return nil
    InstanceID.instanceID().instanceID { (result, error) in
        if let result = result {
             print("Result:\(String(describing: result?.token))")
    } else {
            print("Error:\(error))")
    } //returns after about 2 mins with an firebase iid error of 1003

}

1 Ответ

0 голосов
/ 15 сентября 2018

Пожалуйста, проверьте приведенный ниже код делегата приложения.

import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications


class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()



    //REMOTE NOTIFICATION

    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    Messaging.messaging().delegate = self

    let token = Messaging.messaging().fcmToken
    print("FCM token: \(token ?? "")")



    //Added Code to display notification when app is in Foreground
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().delegate = self
    } else {
        // Fallback on earlier versions
    }
    return true
}



func application(_ application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken as Data
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    // Print full message.
    print(userInfo)
}



// This method will be called when app received push notifications in foreground
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
    completionHandler([UNNotificationPresentationOptions.alert,UNNotificationPresentationOptions.sound,UNNotificationPresentationOptions.badge])
}


// MARK:- Messaging Delegates
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    InstanceID.instanceID().instanceID { (result, error) in
        if let error = error {
            print("Error fetching remote instange ID: \(error)")
        } else if let result = result {
            print("Remote instance ID token: \(result.token)")
        }
    }
}

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("received remote notification")
    }
}
...