I'm implementing socket.io
in my swift ios app.
Currently on several panels I'm listening to the server and wait for incoming messages. I'm doing so by calling the getChatMessage
function in each panel:
func getChatMessage(){
SocketIOManager.sharedInstance.getChatMessage { (messageInfo) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//do sth depending on which panel user is
})
}
}
However I noticed it's a wrong approach and I need to change it - now I want to start listening for incoming messages only once and when any message comes - pass this message to any panel that listens to it.
So I want to pass the incoming message through the NSNotificationCenter. So far I was able to pass the information that something happened, but not pass the data itself. I was doing that by:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.showSpinningWheel(_:)), name: showSpinner, object: nil)
then I had a function called:
func showSpinningWheel(notification: NSNotification) {
}
and any time I wanted to call it I was doing:
NSNotificationCenter.defaultCenter().postNotificationName(hideSpinner, object: self)
So how can I pass the object messageInfo
and include it in the function that gets called?
For Swift 3
For Swift 4
Swift 2.0
Pass info using
userInfo
which is a optional Dictionary of type [NSObject : AnyObject]?Swift 3.0 version
The userInfo now takes [AnyHashable:Any]? as an argument, which we provide as a dictionary literal in Swift
NOTE: Notification “names” are no longer strings, but are of type Notification.Name, hence why we are using
NSNotification.Name(rawValue:"notificationName")
and we can extend Notification.Name with our own custom notifications.Hello @sahil I update your answer for swift 3
Hope it's helpful. Thanks
let dictionary = self.convertStringToDictionary(responceString)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SOCKET_UPDATE"), object: dictionary)