如何等待AppDelegate中的事件完成(快速)

时间:2018-12-05 05:09:12

标签: ios swift

来自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值更改时立即更新UI)

1 个答案:

答案 0 :(得分:0)

使用NSNotificationCenter将通知广播到其他班级几乎完成了。

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"]
    }
}