实现自定义消息收发
更新时间: 2025/09/11 14:15:56
网易云信即时通讯 IM SDK 内置了包括图片,音频,视频等多媒体消息,但基于不同的应用场景,您可能需要某些特殊的消息类型,因此需要自定义消息类型。本文介绍了如何从 Model 到绘制 UI,一步步实现自定义消息类型。
IM UIKit 的会话消息模块(NEChatUIKit)默认实现了文本消息、图片消息等 基本消息类型 的发送和展示。如果这些消息类型无法满足您的业务需求,您可 新增自定义消息类型。
消息类型
应用中常见的基本消息类型如下所示:
| 消息类型 | 显示效果 | 是否需要额外集成 |
|---|---|---|
| 文本消息 | ![]() |
否,集成会话界面即可用 |
| 图片消息 | ![]() |
|
| 语音消息 | ![]() |
|
| 视频消息 | ![]() |
|
| 表情 | ![]() |
|
| 文件消息 | ![]() |
否,集成会话界面即可用单击点开查看配置步骤。请在 XCode 中,选择 TARGETS -> Signing&Capabilities -> iCloud,然后勾选 iCloud Documents。![]() |
| 地理位置 | ![]() |
是,参考 实现地理位置消息功能 |
前提条件
根据本文操作前,请确保您已经 集成会话消息界面。
第一步:创建自定义消息
Swift // type 字段必须指定,且不可为 101、102(UIKit 内部已使用),否则解析为 **未知消息体**
let dataDic: [String: Any] = ["type": customMessageType]
let dataJson = NECommonUtil.getJSONStringFromDictionary(dataDic)
let customMessage = MessageUtils.customMessage(text: "this is a custom message",
rawAttachment: dataJson)
自定义消息附件 JSON 中的 type 字段必须指定,用于内部解析以及绑定 cell,从而实现不同类型的自定义消息的对应展示。
第二步:发送自定义消息
自定义消息的发送与其他消息类型的发送相同。
Swift ChatRepo.shared.sendMessage(message: customMessage, conversationId: viewModel.conversationId) { result, error, pro in
if let err = error {
print("send custom message error : ", err.localizedDescription)
}
}
第三步:接收自定义消息
当收到一条自定义消息时,您需要自行解析消息中的 attachment 对象(V2NIMMessageAttachment)的 raw 字段。
IM UIKit 提供了自定义消息解析工具类 NECustomUtils,您可以快速解析 type、data 等自定义字段。
Swift/// 收到消息
/// - Parameter messages: 消息列表
open func onRecvMessages(_ messages: [V2NIMMessage], _ indexs: [IndexPath]) {
if let message = messages.first {
// 解析自定义消息 attachment
let attachment = NECustomUtils.attachmentOfCustomMessage(message.attachment)
// 解析自定义消息 data 字段
let data = NECustomUtils.dataOfCustomMessage(message.attachment)
// 解析自定义消息 type 字段
let type = NECustomUtils.typeOfCustomMessage(message.attachment)
...
}
}
注意事项
当通过 服务端 API 发送自定义消息时,为确保客户端能够正确识别和解析不同类型的自定义消息,您需要按照特定格式构造 attachment 字段的JSON内容。
自定义消息的 attachment 字段应遵循以下 JSON 格式:
JSON{
"type": 1002,
"data": {
"customer_message_key": "这是一条自定义消息"
}
}
字段说明
| 字段 | 类型 | 说明 |
|---|---|---|
type |
Integer | 自定义消息类型标识,用于客户端区分不同类型的自定义消息,必须 与客户端定义的类型保持一致。 |
data |
JSON 对象 | 自定义消息的业务数据载体,可包含任意自定义的键值对。 |
自定义消息展示
如果您需要在会话界面添加发送自定义消息的 UI 控件,可在单击 更多 按钮(见下图)后展示的区域增加相应的按钮。详情请参考 自定义会话消息界面 UI。
自定义单元格(TableviewCell)
您可自定义单元格,实现自定义消息的自定义展示。
实现步骤与示例代码(Swift):
-
继承
NEChatBaseCell类,实现自定义单元格,对自定义消息进行展示。Swiftclass CustomChatCell: NEChatBaseCell { public var testLabel = UILabel() ... override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none backgroundColor = .lightGray testLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(testLabel) NSLayoutConstraint.activate([ testLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), testLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), ]) testLabel.font = UIFont.systemFont(ofSize: 14) testLabel.textColor = UIColor.black } override func setModel(_ model: MessageContentModel, _ isSend: Bool) { if let model = model as? MessageCustomModel { print("this is custom message, customType: \(model.customType)") testLabel.text = model.message?.text // 解析自定义消息 attachment let attachment = NECustomUtils.attachmentOfCustomMessage(model.message?.attachment) // 解析自定义消息 data 字段 let data = NECustomUtils.dataOfCustomMessage(model.message?.attachment) // 解析自定义消息 type 字段 let type = NECustomUtils.typeOfCustomMessage(model.message?.attachment) ... } } } -
继承
P2PChatViewController类,绑定自定义消息cell。Swiftclass CustomP2PChatViewController: P2PChatViewController { let customMessageType = 20 // 自定义消息附件 JSON 中的 type 字段,用于绑定 cell,从而实现不同类型的自定义消息的对应展示 override func viewDidLoad() { // 自定义消息 cell 绑定需要放在 super.viewDidLoad() 之前 NEChatUIKitClient.instance.regsiterCustomCell(["\(customMessageType)": CustomChatCell.self]) ... super.viewDidLoad() } }regsiterCustomCell方法的入参类型为[String: UITableViewCell.Type],其中key需要与自定义消息中的type相对应,从而实现不同类型的自定义消息的对应展示。 -
发送自定义消息。
Swift// type 字段必须指定,且不可为 101、102(UIKit 内部已使用),否则解析为 **未知消息体** let dataDic: [String: Any] = ["type": customMessageType] let dataJson = NECommonUtil.getJSONStringFromDictionary(dataDic) let customMessage = MessageUtils.customMessage(text: "this is a custom message, create time:\(Date.timeIntervalSinceReferenceDate)", rawAttachment: dataJson) ChatRepo.shared.sendMessage(message: customMessage, conversationId: viewModel.conversationId) { result, error, pro in if let err = error { print("send custom message error : ", err.localizedDescription) } }自定义消息附件 JSON 中必须指定 type 字段,用于内部解析以及绑定 cell,从而实现不同类型的自定义消息的对应展示。
-
修改自定义 cell 高度。
Swiftclass CustomP2PChatViewController: P2PChatViewController { let customMessageType = 20 ... /// 获取消息模型,可在此处对消息体进行修改 /// - Parameter model: 模型 override func getMessageModel(model: any MessageModel) { super.getMessageModel(model: model) // 例如设置自定义消息高度 if model.type == .custom { if model.customType == customMessageType { // 设置气泡宽高,不设置则不展示气泡 model.contentSize = CGSize(width: 20, height: 20) // 设置 cell 高度 model.height = 50 } } } }消息展示前,可在
getMessageModel方法中对消息进行修改,例如设置自定义消息 cell 的高度。 如果在构建自定义消息附近 JSON 时设置了type字段,则 UIKit 能够正确解析该自定义消息,customType用于存储自定义消息子类型,可用于区分不同的自定义消息。













