使用 MessageKit 和 Socket IO 开发聊天功能
场景最初是收到消息文本和图像,但是一旦返回然后再次连接套接字并尝试接收文本消息不起作用但收到图像消息。
在以前的视图控制器中,如果其状态为已连接,我将断开套接字。
调试后,第二次获取套接字并更新了 messageList 但重新加载集合视图不起作用并更新单元格
从套接字获取聊天短信:
socket.connect()
socket.on(clientEvent: .connect) {data, ack in
socket.emit("login", [ "userId": "\(self.defaults.value(forKey: BDConstant.kUserSellerId) ?? "")"])
socket.on("login") { ( dataArray, ack) -> Void in
print("live chat list seller ids:\(dataArray[0])")
}
//Get receiver message from socket
socket.on("chat text") { ( dataArray, ack) -> Void in
if !dataArray.isEmpty{
var senderType = "" //receiver or sender
///Get data from socket
var arrOuterObject : Array<Any>
arrOuterObject = dataArray[0] as! Array<Any>
var arrInnerObject : Array<Any>
arrInnerObject = arrOuterObject[0] as! Array<Any>
let txt = arrInnerObject[0]
let toMessage : String
let fromMessage: String
//var message:MockMessage?
toMessage = arrOuterObject[1] as! String
fromMessage = arrOuterObject[2] as! String
var strFromSellerId = ""
var strSellerId = "\(self.defaults.value(forKey: BDConstant.kUserSellerId) ?? "")"
if let fromSellerId = fromMessage as? String{
strFromSellerId = fromSellerId
}
if !strSellerId.isEmpty && !strFromSellerId.isEmpty{
if strSellerId == strFromSellerId{
senderType = "apple"
}else{
senderType = "orange"
}
let text = txt as? String
if text != ""{
let user = MockUser(senderId: senderType, displayName: "")
let uniqueID = UUID().uuidString
let now = Date()
let message = MockMessage(text:text!, user: user, messageId: uniqueID, date:now)
self.messages.append(message)
}
DispatchQueue.main.async {
self.messageList = self.messages
self.messagesCollectionView.reloadData()
self.messagesCollectionView.scrollToLastItem()
}
} else {
print("Error")
}
}
}
}
从套接字获取聊天图像消息:
socket.on("chat message") { ( dataArray, ack) -> Void in
if !dataArray.isEmpty{
var multi:String = ""
var action:String = ""
var buyerid:String = ""
var ftime:String = ""
var image:String = ""
var message:String = ""
var sellerid:String = ""
var platformtype:String = ""
var docodedImage = UIImage()
var senderType = "" //receiver or sender
let chatDictionary = dataArray[0] as? [String: Any]
if let Multi = chatDictionary?["Multi"] as? String{
multi = Multi
}
if let Action = chatDictionary?["action"] as? String{
action = Action
}
if let Buyerid = chatDictionary?["buyerid"] as? String{
buyerid = Buyerid
}
if let Ftime = chatDictionary?["ftime"] as? String{
ftime = Ftime
}
if let Image = chatDictionary?["image"] as? String{
image = Image
}
if let Sellerid = chatDictionary?["sellerid"] as? String{
sellerid = Sellerid
}
if let Platformtype = chatDictionary?["plateform_type"] as? String{
platformtype = Platformtype
}
///orange - receiver
///apple - sender
do {
if !action.isEmpty && !image.isEmpty{
if let dataDecoded : Data = Data(base64Encoded: image, options: .ignoreUnknownCharacters){
guard let dataToImage = UIImage(data: dataDecoded) else { return }
docodedImage = dataToImage
}else{
print("error dataDecoded")
}
let strSellerId = "\(self.defaults.value(forKey: BDConstant.kUserSellerId) ?? "")"
if strSellerId == sellerid{
senderType = "apple"
}else{
senderType = "orange"
}
let user = MockUser(senderId: senderType, displayName: "")
let uniqueID = UUID().uuidString
let now = Date()
let message = MockMessage(image: docodedImage, user: user, messageId: uniqueID, date: now)
self.messages.append(message)
DispatchQueue.main.async {
self.messageList = self.messages
self.messagesCollectionView.reloadData()
self.messagesCollectionView.scrollToLastItem()
}
}
}catch{
print("error :\(error)")
}
}
}