B Dub
B Dub

Reputation: 41

Swift 4, Firebase 5.8.0 FCM token nil

I am setting up push notifications, and everything is going well until I try to get the FCM token so I can send a test message to an actual device. Using the pods Firebase 5.8.0, FirebaseCore (5.1.3), FirebaseInstanceID (3.2.1), and FirebaseMessaging (3.1.2), I can get the APNS token fine but every time I try to get the FCM token, it comes out as nil or when I use InstanceID.instanceID().instanceID(handler:) it results in some timeout error code 1003 and a result of nil. didReceiveRegistrationToken does not get called either. I've tried a many 2017 solutions but they're either deprecated or don't work. MessageDelegate and UNUserNotificationCenterDelegate are set, push notifications, and keychain sharing are enabled in capabilities, method swizzling is off via p-list and Here is my didRegisterForRemoteNotificationsWithDeviceToken function where I correctly get the apns token. Any ideas? Thanks.

`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

}

Upvotes: 3

Views: 4081

Answers (1)

Yogesh Tandel
Yogesh Tandel

Reputation: 1754

Please check the below app delegate code.

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

Upvotes: 3

Related Questions