我在我的swift ios應用中實現了socket.io
。如何使用Swift 3.0中的NotificationCentre和Swift 2.0中的NSNotificationCenter傳遞數據?
目前在幾個面板上我正在監聽服務器並等待收到的消息。我通過調用每個面板的getChatMessage
功能這樣做:
func getChatMessage(){
SocketIOManager.sharedInstance.getChatMessage { (messageInfo) -> Void in
dispatch_async(dispatch_get_main_queue(), {() -> Void in
//do sth depending on which panel user is
})
}
}
但是我注意到這是一個錯誤的做法,我需要去改變它 - 現在我要開始監聽傳入的消息只有一次,當任何消息來 - 將此消息傳遞給任何偵聽它的面板。
所以我想通過NSNotificationCenter傳入消息。到目前爲止,我能夠傳遞發生了什麼事情的信息,但不傳遞數據本身。我是這樣做的:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.showSpinningWheel(_:)), name: showSpinner, object: nil)
然後我有一個調用的函數:
func showSpinningWheel(notification: NSNotification) {
}
,我想叫它我做的任何時間:
NSNotificationCenter.defaultCenter().postNotificationName(hideSpinner, object: self)
所以,我怎麼能傳遞對象messageInfo
並將其包含在被調用的函數中?
用戶信息的使用方法...'NSNotificationCenter.defaultCenter()。postNotificationName(「hideSpinner」,object:nil,userInfo:yourvalue)' –
hm好的,我該如何在函數中獲取這個'yourValue'被通知調用(在'showSpinningWheel'中)? – user3766930
使用'.userinfo'就像'notification.userinfo' –