如何在消息发送前后拦截消息
更新时间: 2025/05/15 14:18:36
本文主要介绍如何在消息发送前/后进行拦截。
- 自定义代码需放在消息发送之前,建议放在 application(_:didFinishLaunchingWithOptions:) 中。
- 重写 beforeSend 与 beforeSendCompletion 方法不会生效。
- 完整的实例代码参考:
Custom/CustomConfig.swift。
消息发送前拦截
可在回调中更改消息内容,或者拦截特定消息。
Swift/// 消息列表发送消息前的回调
/// 回调参数:消息参数(包含消息和发送参数)和消息列表的视图控制器
/// 返回值/回调值:(修改后的)消息参数,若消息参数为 nil,则表示拦截该消息不发送
/// beforeSend 与 beforeSendCompletion 只能二设一,同时设置时优先使用 beforeSend
ChatKitClient.shared.beforeSend = { viewController, param in
param.message.text = (param.message.text ?? "") + "[拦截1]"
return param
}
ChatKitClient.shared.beforeSendCompletion = { viewController, param, completion in
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: DispatchWorkItem(block: {
param.message.text = (param.message.text ?? "") + "[拦截2]"
completion(param)
}))
}
消息发送后拦截
可在回调中获取消息反垃圾结果。
Swift/// 本端发送消息后的回调,为 sendMessage 接口callback,可在回调中获取消息反垃圾结果
/// - Parameter completion: sendMessage 接口调用回调
ChatKitClient.shared.sendMessageCallback = { viewController, result, error, progress in
if let antispamResult = result?.antispamResult {
viewController.showToast("反垃圾结果:\(antispamResult)")
}
}
此文档是否对你有帮助?




