Как получить токен устройства с помощью firebase? - PullRequest
0 голосов
/ 16 мая 2019

В старых проектах я получаю токен устройства при первой установке приложения или обновляю токен. Но теперь я создаю новый проект и пишу код для зарегистрированного делегата токена устройства и спрашиваю разрешения, но теперь зарегистрированный токен устройства не вызывается в быстрой версии 4.2. Кто-нибудь сталкивался с этой проблемой? Если да, то каково решение?

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:.
    }


}

Ответы [ 3 ]

2 голосов
/ 16 мая 2019

Тебе тоже нужно сделать это, получить жетон огненной базы

  1. Объявите переменную в своем классе AppDelegate.

    var firebaseToken: String = "" 
    
  2. Вызовите эти методы в вашей didFinishLaunchingWithOptions функции

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
        FirebaseApp.configure()
        self.registerForFirebaseNotification(application: application)
        Messaging.messaging().delegate = self
        return true
    }
    
  3. Добавьте эту функцию в свой класс AppDelegate.

    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. И Last создают расширение AppDelegate и добавляют эти функции

    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)")
    
    
     }
    }
    
0 голосов
/ 16 мая 2019

Те же методы в swift помогут вам отследить данные делегата токена

- (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;
}
0 голосов
/ 16 мая 2019

Вы должны вызвать следующую функцию, чтобы получить токен fcm,

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

и отредактировать didFinishLaunchingWithOptions() appDelegate как,

 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
}
...