Хранить токен Firebase Cloud Messaging в классе ViewModel SwiftUI

avatar
krish
8 августа 2021 в 19:36
182
1
0

Я пытаюсь интегрировать FirebaseCloud Messaging в свое приложение IOS в Swift/SwiftUI. Я пытался сохранить FCMtoken вне класса App Delegate, но не знаю, как получить значение. Я пытался создать переменную Appstorage для ее обновления, но безрезультатно.

Вот как сейчас устроен мой App Delegate:


// intializing Firebase...

class AppDelegate: NSObject,UIApplicationDelegate, ObservableObject{
    let gcmMessageIDKey = "gcm.message_id"
    
    //want to call a method to update the token from this swift class
    @StateObject var registerData = RegisterViewModel()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        
        FirebaseApp.configure()
       
        return true
    }
    
    func registerForPushNotifications() {
        //set up messaging delegate comment for simulator and gets token
        Messaging.messaging().delegate = self
//        NotificationCenter.default.addObserver(self, selector: #selector(getNotification), name: Notification.Name(rawValue: "FCMToken"), object: nil)

        //register for push notif
        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)
            UIApplication.shared.registerUserNotificationSettings(settings)
        }

        UIApplication.shared.registerForRemoteNotifications()
       
        
    }
    
    func application(_ application: UIApplication,
                     didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult)
                       -> Void) {
        //DO somehing with message
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
          }

          // Print full message.
          print(userInfo)

          completionHandler(UIBackgroundFetchResult.newData)
    }
    
    
 
    //FOR firebase phone auth silent APN
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
      // Pass device token to auth
      Auth.auth().setAPNSToken(deviceToken, type: .prod)
        
    }
    //No callback in simulator
    //-- must use device to get valid push token
 
     func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
       print(error.localizedDescription)
    }
    

    
    
    
   
}

//cloud messaging comment for simulator
extension AppDelegate: MessagingDelegate {

    
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {

      let dataDict: [String: String] = ["token": fcmToken ?? ""]
      //NEED to pass this variable device_token to another SwiftUI View
       let device_token = dataDict["token"]!
        
        
    }

  
}

Я пытаюсь сохранить эту переменную device_token в расширении обмена сообщениями в других представлениях. Как мне это сделать? Спасибо!

Источник
El Tomato
8 августа 2021 в 21:13
0

Сначала сохраните его в переменной AppDelegate. Затем получите доступ к нему из ViewModel или любого другого парня, на которого вы ссылаетесь.

Ответы (1)

avatar
srinij
18 августа 2021 в 23:14
0

Посмотрите на это из документации

You can use this method at any time to access the token instead of storing it. согласно документации.