Issue while handle user typing notification using

2019-07-29 12:47发布

问题:

I am creating an chat application using socket.io, every things going perfect but when I am handling user typing notification I am getting error like below

Error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SocketChat.ChatViewController handleUserTypingNotification:]: unrecognized selector sent to instance 0x7f817653d710

and now I will show you my code for better expiation

Code:

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

Here I am managing method which I am getting from index.js file and from another viewcontroller. I manage with notification center like bellow

let notificationCenter4 = NotificationCenter.default
        notificationCenter4.addObserver(self, selector: Selector(("handleUserTypingNotification")), name:NSNotification.Name(rawValue: "userTypingNotification"), object: nil)

I don't understand why this error is coming and what does it exactly mean. Can any one please help me?

import UIKit

class ChatViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let notificationCenter4 = NotificationCenter.default
        notificationCenter4.addObserver(self, selector: #selector(handleUserTypingNotification)), name:NSNotification.Name(rawValue: "userTypingNotification"), object: nil)
    }

    func handleKeyboardDidShowNotification(notification: NSNotification) {
        if let userInfo = notification.userInfo {
            if let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
                conBottomEditor.constant = keyboardFrame.size.height
                view.layoutIfNeeded()
            }
        }
    }

}

回答1:

Your selector signature is wrong. It should look like this.

let notificationCenter4 = NotificationCenter.default
notificationCenter4.addObserver(self, selector: #selector(handleKeyboardDidShowNotification(notification:)), name:NSNotification.Name(rawValue: "userTypingNotification"), object: nil)

In your code you are creating a new instance, while you probably have a selector already. Something like this.

@objc func handleKeyboardDidShowNotification(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        if let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            conBottomEditor.constant = keyboardFrame.size.height
            view.layoutIfNeeded()
        }
    }
}