![](/img/trans.png)
[英]how to do to wait to load ViewController until appdelegate func application will be completed
[英]How to wait for an event in AppDelegate to be completed (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)
使用NSNotificationCenter
Notification廣播到其他類幾乎完成了。
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
您是否在viewDidLoad
函數中為該通知Notification.Name("FCMToken")
添加了觀察者?
如果沒有,請如下添加。
// 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"]
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.