Toshi
Toshi

Reputation: 1303

How to update data on swift immediately

I'd like to update likeNum data on swift immediately after a like button is pressed. At the following tapLike function, I've updated the likeNum data at server side (written by rails), then reload data by self.tableView.reloadData(). However, it cannot update the shown data simultaneously. Could you tell me how to update data at immediately?

func tapLike(recognizer: UITapGestureRecognizer){
        var userId = self.defaults.objectForKey("uid") as! Int
        let parameters = [
            "id": recognizer.view!.tag,
            "user_id": userId
        ]

        Alamofire.request(.POST, uri.answersApi + "/like", parameters: parameters, encoding: .JSON)
            .responseJSON { (request, response, data, error) in
                self.tableView.reloadData()
        }
    }
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("qaIdentifier", forIndexPath: indexPath) as! QATableViewCell
    cell.likeNum.text = String(answers[indexPath.row].likeNum!)
    return cell
}

Upvotes: 0

Views: 221

Answers (1)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71852

The UI should only be updated from main thread:

dispatch_async(dispatch_get_main_queue()) {
    self.tableView.reloadData()
}

Upvotes: 2

Related Questions