3

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579

2 Answers2

14

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)
zisoft
  • 22,770
  • 10
  • 62
  • 73
5

In my case i can't get NotificationCenter in some situation in my app . and problem was that using

NotificationCenter.default.addObserver(self, selector: #selector(btnRegister(_:)), name: Notification.Name(rawValue: "btnRegister"), object: nil)

in my viewDidLoad() func, And when i set above code in my viewWillAppear() func, that's work perfectly.

According to your code logic , move above code to other func or other section of your code and try to fix your problem.

Hamid Reza Ansari
  • 1,107
  • 13
  • 16