UITableView got rendered before API returned using SwiftyJSON and Alamofire

when i call the callapi () function in viewDidLoad (), println () in callapi prints an array of messages with Post objects inside it, however the println () function inside the viewDidLoad () function prints an empty array. Also when I build the project I get this "fatal error: array index out of range" error. the println () statement in the tableView function also prints an empty array. It seems the table was processed before the data from the API showed up, how can I solve this?

var posts = [Post]()

override func viewDidLoad() {
    super.viewDidLoad()
    callapi()
    println(self.posts)
}

func callapi(){
    request(.GET, "url")
    .responseJSON { (request, response, data, error) in
        let json = JSON(data!)
        if let jsonArray = json.array {
            for post in jsonArray {
                var onepost = Post(id:post["id"].stringValue,                    

              title:post["title"].stringValue, 
              author:post["author"].stringValue, 
              post:post["post"].stringValue,   
              created_on:post["created_on"].stringValue, 
              updated_on:post["updated_on"].stringValue)
                self.posts.append(onepost)
                println(self.posts)
                self.tableView.reloadData()
            }
        }
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath
 indexPath: NSIndexPath) -> UITableViewCell {
    let cellIdentifier = "Cell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier,
    forIndexPath: indexPath) as! CustomTableViewCell

    println(self.posts)
    let post = self.posts[indexPath.row]
    // Configure the cell...
    cell.titleLabel!.text = self.posts[indexPath.row].title
    cell.postLabel.text = post.post
    println(self.posts)
    return cell
}

      

+3


source to share


3 answers


When called viewDidLoad

, it starts asynchronous callapi

, but is viewDidLoad

posts

still empty when finished . But the table view will still continue the boot process even though it has posts

n't been populated, so you have to make sure to tableView:numberOfRowsInSection:

return zero at this point.

Later callapi

, Alamofire completes the request GET

and calls reloadData

. tableView:numberOfRowsInSection:

Returns a nonzero value only at this point .



On the bottom line, make sure it tableView:numberOfRowsInSection:

returns the actual number of records in posts

and the issue should be resolved.

+1


source


Just insert the reload into viewDidAppear and you're good to go:



override func viewDidAppear(animated: Bool) {
        self.tableView.reloadData()
    }

      

+2


source


make sure you set tableView: numberOfRowsInSection: to return self.posts.count

0


source







All Articles