ios - 使用 notificatincenter 处理用户键入通知时出现问题

标签 ios swift notificationcenter

我正在使用 socket.io 创建一个聊天应用程序,一切都很完美,但是当我处理用户输入通知时,出现如下错误

错误:

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

现在我将向您展示我的代码以便更好地赎罪

代码:

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

我在这里管理从 index.js 文件和另一个 View Controller 获取的方法。我像下面这样使用通知中心进行管理

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

我不明白为什么会出现此错误以及它的确切含义。谁能帮帮我?

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()
            }
        }
    }

}

最佳答案

您的选择器签名有误。它应该看起来像这样。

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

在您的代码中,您正在创建一个 实例,而您可能已经有了一个选择器。像这样。

@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()
        }
    }
}

关于ios - 使用 notificatincenter 处理用户键入通知时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52233830/

相关文章:

ios - 如何使用自定义设计显示一串数字?

iphone - ios 将 ipad 应用程序转换为通用显示此错误 Nib 但未设置 View socket

swift - 尝试根据 UILabel 的文本大小更新父 View 框架

ios - 检查 FaceID 是否启用

swift - 可以使用条件来确定泛型的类型吗?

macos - 复制像《Mountain Lion》中的通知中心一样向一侧滑动的屏幕?

objective-c - 制作离屏可拖动 View (如 iOS 5 通知中心)

ios - 找不到“folly/folly-config.h”文件

ios - 通知中心 - 无法将类型 'Selector' 的值转换为预期参数类型 'String'

ios - 如何关闭文本字段中的键盘