在表视图中显示来自后端服务的数据

时间:2016-02-26 15:47:35

标签: swift telerik backend mbaas

我从正在返回消息对象的后端服务中获取数据,并且我想在表视图中显示消息。我遇到的问题是re是加载视图和数据到达之间的延迟。目前,用户滚动表格视图时会立即显示消息。

override func viewDidLoad() {
    super.viewDidLoad()
    print("Message view did load")
    username = preferences.valueForKey("username") as! String
    userID = preferences.valueForKey("userID") as! String

    // Do any additional setup after loading the view.
    self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    self.tableView.rowHeight = UITableViewAutomaticDimension

    getUser()
}

func getUser(){
    let currentUserAccessToken = EVUser.currentUser().accessToken
    EVUser.fetchWithAccessToken(currentUserAccessToken, block: { (loggedInUser:EVUser!, error:NSError!) -> Void in
        if (error == nil) {
            self.user = loggedInUser
            self.getMessages()
            print("The user " + loggedInUser.username + " is logged in with valid access token.")
        } else {
            print("The user is not logged in: " + error.domain)
        }
    })

}

func getMessages(){

    let dataStore: EVDataStore = EVDataStore.sharedInstance() as! EVDataStore

    //Filter item
    let request:EVFetchRequest = EVFetchRequest(kindOfClass: Message.self)

    request.predicate = NSPredicate(
        format: "CreatedByName == %@ OR (To == %@ AND CreatedByName == %@)",
        username,
        userID,
        "Admin"
    )
    dataStore.executeFetchRequest(request, block: { (result, error ) -> Void in
        if error == nil{
            if  result?.count > 0 {

                for item in result{
                    print (item)
                    self.globalMessages.append(item as! Message)
                }
                self.displayMessages(self.globalMessages)

            }else{
                print("No items found")
            }
        }else{
            print("Error: \(error)")
        }
    })
}


func displayMessages(messages:[Message]){
    setupTableView()
}


func setupTableView(){
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

有没有办法在消息到达后立即将消息添加到表视图中?

1 个答案:

答案 0 :(得分:1)

您有多个选项可以执行此操作。以太,您正在重新加载整个表视图或插入一行。

重新加载表格视图

tableView.reloadData()

插入行

tableView.beginUpdates()
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: {your message array}.count-1, inSection: 0)], withRowAnimation: .Automatic)
tableView.endUpdates()

有关详细信息,请查看此处:Insert new cell into UITableView