swift - 类型错误 : Cannot read property 'messageBody' of undefined

标签 swift api heroku websocket socket.io

我想使用

通过 api 在我的应用程序中发送消息

( https://github.com/devslopes-learn/mac-chat-api )

当我尝试发送消息时,我总是在 Heroku 终端日志中收到此错误:

enter image description here

我尝试了一切,但似乎无法弄清楚为什么会发生这种情况。 顺便说一句,我正在 Udemy 上的类(class)中学习这个 api。

这是我的发射:

func sendMessage(messageBody: String, userId: String, channelId: String, completion: @escaping CompletionHandler) {
    let user = UserDataService.instance
    socket.emit("newMessage", messageBody, userId, channelId, user.name, user.avatarName, user.avatarColor)
    completion(true)
}

这里我使用这个函数:

@IBAction func sendMsgPressed(_ sender: Any) {
    if AuthService.instance.isLoggedIn {
        guard let channelId = MessageService.instance.selectedChannel?.id else { return }
        guard let message = messageTxtField.text else { return }

        SocketService.instance.sendMessage(messageBody: message, userId: UserDataService.instance.id, channelId: channelId) { (success) in
            if success {
                self.messageTxtField.resignFirstResponder()
                self.messageTxtField.text = ""
            }
        }
    }
}

最佳答案

查看 Swift 的 SocketIOClient API 文档 here ,您没有传递正确的符合 SocketData 对象类型,而是传递单独的参数。您应该为您的数据创建一个符合 SocketData 的对象,以确保您的数据可以在 socket.io 数据包中表示。下面基本上是他们文档中示例的重述:

struct CustomData: SocketData {
   let messageBody: String
   let userId: Int
   let channelId: Int
   let userName: String
   let avatarColor: String

   func socketRepresentation() -> SocketData {
       return [
           "messageBody": name, 
           "userId": userId,
           "channelId": channelId,
           "userName": userName,
           "avatarColor": avatarColor,
       ]
   }
}

let customData = CustomData(...)
socket.emit("newMessage", customData)

关于swift - 类型错误 : Cannot read property 'messageBody' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53090217/

相关文章:

swift - CoreML 模型在 coremltools 和 Xcode 之间产生不同的结果

ios - 无法设置视频录制的最长持续时间?

rest - 在 Ubuntu/Centos 上部署并运行 Go API 服务器

javascript - 使用 JS SDK 创建新的 Soundcloud 播放列表 ( set ) 返回 422

php - 开发 API - 如何使其安全?

ruby-on-rails - 将数据库从 Rails 迁移到 Heroku 中的 Django 应用程序

ios - 在带有 Google Cloud Endpoints 客户端的 iOS Swift 项目中使用 Google API 客户端库

node.js - 创建应用程序后是否可以升级 Heroku 应用程序的 buildpack?

python - 夹层 - 无法在 Heroku 中加载 css 和 js

ios - 评估 UITraitCollection 的 hasDifferentColorAppearance(与 :) result 相比