最近我的 ios Messenger 遇到了一些问题。我一开始只获取短信,一切都很顺利。当我尝试从解析中获取图像时,我成功了;但是,提要的顺序不正确。 看起来它完全忽略了“query.orderByAscending”......
fetchMessages()
{
currentUser = PFUser.currentUser()!
let query = PFQuery(className:"Messages")
query.whereKey("convoid", equalTo:convoid)
query.orderByAscending("createdAt")
query.cachePolicy = .NetworkElseCache
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
dispatch_async(dispatch_get_main_queue()) {
if let objects = objects {
for object in objects {
if(object["fileType"] as? String == "photo"){
if(object["senderId"] as? String == self.currentUser.objectId!){
let userImageFile = object["file"] as! PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
let imageddata = UIImage(data:imageData!)
let chatBubbleData = ChatBubbleData(text: "", image:imageddata, date: object.createdAt, type: .Mine)
self.addChatBubble(chatBubbleData)
self.chatBubbleDatas.append(chatBubbleData)
}
}
}else{
let userImagefile = object["file"] as! PFFile
userImagefile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
let imageddata = UIImage(data:imageData!)
let chatBubbleData = ChatBubbleData(text: "", image:imageddata, date: object.createdAt, type: .Opponent)
self.addChatBubble(chatBubbleData)
self.chatBubbleDatas.append(chatBubbleData)
}
}
}
}else{
if(object["senderId"] as? String == self.currentUser.objectId!){
let chatBubbleData = ChatBubbleData(text: object["text"] as? String, image:nil, date: object.createdAt, type: .Mine)
self.addChatBubble(chatBubbleData)
self.chatBubbleDatas.append(chatBubbleData)
}else{
let chatBubbleData = ChatBubbleData(text: object["text"] as? String, image:nil, date: object.createdAt, type: .Opponent)
self.addChatBubble(chatBubbleData)
self.chatBubbleDatas.append(chatBubbleData)
}
}
}
}
}
} else {
print("Error: \(error!) \(error!.userInfo)")
}
}
self.messageCointainerScroll.contentSize = CGSizeMake(CGRectGetWidth(messageCointainerScroll.frame), lastChatBubbleY + internalPadding)
self.addKeyboardNotifications()
}
除了消息 View 没有以正确的顺序显示所有消息之外,一切都运行良好。事实上,所有文本消息的顺序都是正确的,但无论什么情况,无论创建日期如何,消息图像总是在后面。我认为它必须与加载有关;然而我知道要 swift ,但我并不完全确定。有关修复或引用的任何见解请分享!
最佳答案
我的第一个猜测是,这与在主队列上执行操作的调用的位置有关:
dispatch_async(dispatch_get_main_queue()) {
您可能只想在最后需要更新用户界面时才这样做。问题是,花费较长时间的操作可能会在花费较少时间的操作之后得到处理,因为整个 block 开始在后台运行(在不同的队列上,因此您不知道调度上的情况如何)主队列...)。
经过进一步检查,您的 block 内似乎有一堆其他后台调用,例如:
userImagefile.getDataInBackgroundWithBlock
我已经使用 Parse 和 JSQMessagesViewController 编写了这样的代码,我认为这就是您正在做的事情。我强烈建议您找到通过网络将用户界面更新与模型更新分离的方法。您现在所拥有的不仅难以调试,而且可能以某种难以检测的异步方式导致您的问题。
关于ios - 解析 Messenger 聊天 Swift : Messages are out of order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34972220/