如何在收到新消息时顺利更新聊天视图

时间:2017-07-25 02:10:00

标签: ios swift multithreading tableview

我对我的聊天应用有疑问 我有一个关于和别人聊天的看法。

chat view like this.

但是当其他人向我发送消息时,我应该更新我的视图以让用户知道新的消息文本,我也在我的sqlite中保存消息。
当用户收到消息时,我在主线程中更新视图 它使视图暂时锁定,我想向我的聊天目标发送消息,我应该等待视图更新结束 一般来说,如何处理更新聊天视图?
感谢。

import UIKit
import RxCocoa
import RxSwift
class ViewController: UIViewController {

    var subscribe:Disposable? 
    var texts:[Message] = [Message]()

    override func viewDidLoad() {
    super.viewDidLoad()

    self.subscribe = chatroom.PublishSubject<Any>().subscribe({ json in

       DispatchQueue.main.async {
            self.loadTexts()
       }
    })
   } 


   func loadTexts() {

        self.texts.removeAll(keepingCapacity: false)
        self.chatroom.messages.forEach({ (id,message) in
            self.texts.append(message)
        })

        self.texts.sort(by: { (a,b) in
            a.time < b.time
        })

        self.tableView.reloadData()
        //updateViewFrame()
        if self.texts.count > 0 {
            self.tableView.scrollToRow(at: IndexPath.init(row: self.texts.count-1,section: 0), at: .bottom, animated: false)
        }

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return texts.count
}

}

2 个答案:

答案 0 :(得分:0)

所有与UI相关的工作必须始终在主线程中运行。

DispatchQueue.global().async() {
  print("Work Dispatched")
  // Do heavy or time consuming work

  // Then return the work on the main thread and update the UI
  DispatchQueue.main.async() {
       // Return data and update on the main thread, all UI calls should be on the main thread 
      self.tableView.reloadData()
  }
}

答案 1 :(得分:0)

DispatchQueue.global(qos: .userInitiated).async {
DispatchQueue.main.async {
                self.chatTableView.dataSource = self
                self.chatTableView.delegate = self
                self.chatTableView.reloadData()
                self.tableViewScrollToBottom(animated: false)
            }
}