2017-07-25 45 views
0

我对我的聊天应用程序有疑问。
我有一个关于与他人聊天的观点。
当我收到新消息时,如何顺利更新聊天视图

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 
} 

} 
+0

DispatchQueue.main.async { self.chatTableView.dataSource =自 self.chatTableView.delegate =自 self.chatTableView.reloadData() self.tableViewScrollToBottom(动画:假) } –

回答

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() 
    } 
} 
+0

好的我已经知道了,但是我的情况呢? – Beginnerrrrrr

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