Search code examples
iossocket.ionsnotificationcenter

NotificationCenter throw error when adding observer with selector function


In the server side I use socket.io library to send some JS object data type through, upon users typing in their devices:

var typingUsers = {};

    clientSocket.on("startType", function(clientNickname){
        typingUsers[clientNickname] = 1;
        io.emit("userTypingUpdate", typingUsers);
    });

when the app receives data, it will post notification:

 private func listenForOtherMessages() {
     socket.on("userTypingUpdate") { (dataArray, socketAck) -> Void in
     NotificationCenter.default.post(name:NSNotification.Name(rawValue: "userTypingNotification"), object: dataArray[0] as! [String: AnyObject])
       }
  }

And then the notification is added to a view controller as an observer:

NotificationCenter.default.addObserver(self, selector: Selector(("handleDisconnectedUserUpdateNotification:")), name: NSNotification.Name(rawValue: "userWasDisconnectedNotification"), object: nil) 

This implementation always throw an error "unrecognised selector send to ..."

But the following implementation without a selector works ok:

NotificationCenter.default.addObserver(forName:NSNotification.Name(rawValue: "userTypingNotification"), object: nil, queue: nil){ object in
             print(object)

}

It seems like I cannot add an selector to the observer, I think the problems might lie in the object data type, but I cannot really figure out why..


Solution

  • found the answer:

    NotificationCenter.default.addObserver(self, selector: #selector(self.userTypingNotification), name: NSNotification.Name(rawValue: "userWasDisconnectedNotification"), object: nil)
    

    older post