来自C#/ Java / JS,我才刚刚开始学习Swift。我想与FirebaseMessaging一起工作,只是为了学习该语言。

我想在UI中显示FirebaseMessaging中的fcmToken。根据教程,我具有以下AppDelegate扩展名,以等待fcmToken并进行打印。

extension AppDelegate : MessagingDelegate {
    // [START refresh_token]
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")

        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)

        // TODO: If necessary send token to application server
        // Note: This callback is fired at each startup and whenever a new token is generated.

    }
    // [END refresh_token]

    // [START ios_10_data_message]
    // Receive data messages on iOS 10+ directly from FCM (bypassing APNSs) when the app is in the foreground.
    // To enable direct data messages, you can set  Messaging.messaging().shouldEstablishDirectChannel to true.
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Received data message:  \(remoteMessage.appData)")
    }
    // [END ios_10_data_message]
}


在我的视图控制器中,在viewDidLoad中,我只想将fcmToken的值分配给标签,如下所示。

class ViewController: UIViewController {

    // MARK: Properties
    @IBOutlet weak var labelFcmToken: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        ...

        // set FcmToken
        labelFcmToken.text = Messaging.messaging().fcmToken

        ...
    }

    ...
}


问题是didReceiveRegistrationToken似乎也是某种事件侦听器。因此,当调用viewDidLoad时,尚未设置fcmToken。

那么,如何在Swift中等待fcmToken可用,然后在UI中显示它呢?

(在C#中,我可能会将标签绑定到保存fcmToken的某个属性。然后,绑定本身将负责触发事件以在其值更改时立即更新UI)

最佳答案

使用NSNotificationCenter将Notification广播到其他类几乎完成了。

NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)


您是否已在Notification.Name("FCMToken")函数中为该通知viewDidLoad添加了观察者?

如果没有,请如下添加。

// MARK: Properties
@IBOutlet weak var labelFcmToken: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    labelFcmToken.text = Messaging.messaging().fcmToken

    NotificationCenter.default.addObserver(self, selector: #selector(self.fcmTokenUpdated(notification:)), name: Notification.Name("FCMToken"), object: nil)
}

deinit {
    //Don't forget to removeObserver
    NotificationCenter.default.removeObserver(self, name: Notification.Name("FCMToken"), object: nil)
}

@objc func fcmTokenUpdated(notification:Notification){

    if let userInfo = notification.userInfo as? [String: String]{

        labelFcmToken.text = userInfo["token"]
    }
}

09-18 03:55