Search code examples
swifttelerikbackendmbaas

Displaying data from back end service in table view


I am fetching data from a backend service that is returning message objects and i want to display the messages in a table view. the problem i am having is the re is a delay between when the view is loaded and when the data arrives. currently the messages display as soon as the user scrolls the table view.

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;
}

Is there a way to add the messages to the table view as soon as they arive?


Solution

  • You have more than one option to do this. Ether you are reloading the whole table view or you insert a single row.

    Reloading table view

    tableView.reloadData()
    

    Insert a row

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

    For more information look here: Insert new cell into UITableView