在 ViewModel SwiftUI 类中存储 Firebase 云消息传递令牌

Posted

技术标签:

【中文标题】在 ViewModel SwiftUI 类中存储 Firebase 云消息传递令牌【英文标题】:Store Firebase Cloud Messaging Token in ViewModel SwiftUI Class 【发布时间】:2021-08-08 19:36:12 【问题描述】:

我正在尝试在 Swift/SwiftUI 中将 FirebaseCloud Messaging 集成到我的 ios 应用程序中。我一直在尝试将 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 变量存储在其他视图的消息传递扩展中。我该怎么做呢?谢谢!

【问题讨论】:

先将其存入AppDelegate的变量中。然后从 ViewModel 或您所指的任何人访问它。 【参考方案1】:

看看这个from the docs

You can use this method at any time to access the token instead of storing it. 根据文档。

【讨论】:

以上是关于在 ViewModel SwiftUI 类中存储 Firebase 云消息传递令牌的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI 查看内存生命周期

SwiftUI 从 ViewModel 预填充 TextField

在 SwiftUI 组件之间共享 ViewModel

如何在 SwiftUI 中通过 ViewModel 传播模型更改?

基于 VIewModel 状态更新 SwiftUI 视图?

添加 ViewModel 后,SwiftUI 视图未在按钮切换上更新