NotificationCenter obersever not called in swift 4

shraddha k vaishanani picture shraddha k vaishanani · Dec 1, 2017 · Viewed 7.2k times · Source

i am trying to post notification NotificationCenter from appdelegate and receive notification in another view but notification not received.

Post notification :-

func xmppStream(_ sender: XMPPStream, didReceive message: XMPPMessage)
{
    print("did receive message  isss-->\(message)")

    NotificationCenter.default.post(name: Notification.Name("MessageReceived"), object: message)

}

Received Notification in viewdidload :-

 NotificationCenter.default.addObserver(self, selector: #selector(self.messagereceived(notification:)), name: Notification.Name("MessageReceived"), object: nil)

Method :-

@objc func messagereceived(notification:Notification)
{
    let message = notification.object as? XMPPMessage
    print("chat conversion message is----->\(message)")
}

My "messagereceived" Method not called.

so any one have solution related to this then please help me.

Thanks in advance.

Answer

zisoft picture zisoft · Dec 1, 2017

Change the notification post from

 NotificationCenter.default.post(name: Notification.Name("MessageReceived"), object: message)

to

NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: "MessageReceived"),object: message))

and the observer from

NotificationCenter.default.addObserver(self, selector: #selector(self.messagereceived(notification:)), name: Notification.Name("MessageReceived"), object: nil)

to

NotificationCenter.default.addObserver(self, selector: #selector(self.messagereceived(notification:)), name: NSNotification.Name(rawValue: "MessageReceived"), object: nil)