Nikhil Dixit
Nikhil Dixit

Reputation: 1

How to get device token using firebase?

In old projects I have receiving the device token when app install first time or refresh the token. But now I create a new project and write code for did register device token delegate and ask permission but now did register device token is not called in swift version 4.2 . Has anyone faced this issue? If yes, what is solution?

import UIKit
import FirebaseInstanceID
import GoogleMaps
import GooglePlaces
import UserNotifications
import FirebaseCore
import FirebaseMessaging
import Alamofire
import Fabric
import Crashlytics

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate,MessagingDelegate,CLLocationManagerDelegate {

    var window: UIWindow?

    let locationManager = CLLocationManager()
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        if let statusbar = UIApplication.shared.value(forKey: "statusBar") as? UIView {
            statusbar.backgroundColor = UIColor.fromHexaString(hex: "feac1c")
        }

        UIApplication.shared.statusBarStyle = .lightContent

        Fabric.with([Crashlytics.self])


        let remoteNotif = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? NSDictionary

        if remoteNotif != nil
        {

        }
        else
        {
            print("Not remote")
            UNUserNotificationCenter.current().removeAllDeliveredNotifications()
        }

        GMSServices.provideAPIKey(google_url_links().google_mapKey)
        GMSPlacesClient.provideAPIKey(google_url_links().google_mapKey)



        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

                    Messaging.messaging().delegate = self

            })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        FirebaseApp.configure()




         NotificationCenter.default.addObserver(self, selector: #selector(appDelegate.tokenRefereshNotification), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)

        // Override point for customization after application launch.
        return true
    }

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {

        print(remoteMessage.appData)
    }

//    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
//        
//        print("Firebase registration token: \(fcmToken)")
//        UserDefaults.standard.set(fcmToken, forKey: "DeviceToken")
//        
//        
//    }


    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
    {

        Messaging.messaging().apnsToken = deviceToken
        //FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .none)
        //   Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
    }

    @objc func tokenRefereshNotification()
    {
        let refereshtoken  = InstanceID.instanceID().token() ?? ""

        print("token23123::::\(refereshtoken)")
        UserDefaults.standard.set(refereshtoken, forKey: "deviceToken")
        connectToFCM()
    }

    func connectToFCM()
    {
        guard InstanceID.instanceID().token() != nil else
        {
            return
        }

        Messaging.messaging().disconnect()
        Messaging.messaging().connect { (error) in

            if (error != nil)
            {
                print("error unable to connect\(String(describing: error))")
            }
            else
            {
                print("connect to fcm")
            }
        }
    }



    @objc func CheckInterntConnection()
    {
        let alert = UIAlertController(title: "", message: custom_message().error_internet, preferredStyle: UIAlertController.Style.actionSheet)
        alert.addAction(UIAlertAction(title: custom_message().OK, style: UIAlertAction.Style.default, handler: nil))
        self.window?.rootViewController?.present(alert, animated: true, completion: nil)
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

Upvotes: 0

Views: 6298

Answers (4)

PRakash
PRakash

Reputation: 69

Messaging.messaging().token { token, tokenGenerationError in
            if let token = token{
                print("the token is \(token)")
            }
            if let tokenError = tokenGenerationError{
                print("the tokenError is \(tokenError)")
            }
        }

You just code these lines in didFinishLaunchingWithOptions and then run then you can see the Token in print console and use that token in Firebase.

Upvotes: 0

Rohit
Rohit

Reputation: 2326

You need to do this too get firebase Token

  1. Declare a variable in your AppDelegate class.

    var firebaseToken: String = "" 
    
  2. Call these methods in your didFinishLaunchingWithOptions function

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
        FirebaseApp.configure()
        self.registerForFirebaseNotification(application: application)
        Messaging.messaging().delegate = self
        return true
    }
    
  3. Add this function in your AppDelegate class.

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
    }
    
    func registerForFirebaseNotification(application: UIApplication) {
        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()
    }
    }
    
  4. And Last create an extension of AppDelegate and add these functions

    extension AppDelegate: MessagingDelegate, UNUserNotificationCenterDelegate {
    
    //MessagingDelegate
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        self.firebaseToken = fcmToken
        print("Firebase token: \(fcmToken)")
    }
    
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("didReceive remoteMessage: \(remoteMessage)")
    }
    
    //UNUserNotificationCenterDelegate
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("APNs received with: \(userInfo)")
    
    
     }
    }
    

Upvotes: 5

Angel F Syrus
Angel F Syrus

Reputation: 2042

You have to call the following function to get fcm token,

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
  print("Firebase registration token: \(fcmToken)")
  UserDefaults.standard.set(fcmToken, forKey: "DeviceToken")
}

and edit your didFinishLaunchingWithOptions() of appDelegate as,

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    FirebaseApp.configure()
    if(launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] != nil){

    }
    InstanceID.instanceID().instanceID { (result, error) in
        if let error = error {
            print("Error fetching remote instance ID: \(error)")
        } else if let result = result {
            print("Remote instance ID token: \(result.token)")

        }
    }

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

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

    application.registerForRemoteNotifications()

   Messaging.messaging().delegate = self


    return true
}

Upvotes: 0

Vishal Davara
Vishal Davara

Reputation: 91

The same methods in swift will help you to trace token delegate data

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {


    NSLog(@"Unable to register for remote notifications: %@", error);

}

// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the 
//APNs device token can be paired to
// the FCM registration token.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {


    NSLog(@"APNs device token retrieved: %@", deviceToken);
    // With swizzling disabled you must set the APNs device token here.

     [FIRMessaging messaging].APNSToken = deviceToken;
}

Upvotes: 0

Related Questions