-2

When i load a JSON file inside my UITableViewController it loads and updates my datasource and view, but only renders the update when i touch my screen.

The loading and parsing code i'm using looks like this:

func fetchData() {

    let jsonUrl = 'http://myrestserver.com/apicall'
    let session = NSURLSession.sharedSession()
    let urlObject = NSURL(string: jsonUrl)

    let task = session.dataTaskWithURL(urlObject!) {
        (data, response, error) -> Void in
            do {
                let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary

                var items :[Article] = []

                let jsonItems = jsonData["channel"] as! NSArray

                for (_, item) in jsonItems.enumerate() {

                    let article = Article()           
                    article.id = item["id"] as? String
                    article.title = item["title"] as? String
                    article.guid = item["guid"] as? String

                    items.append(article)   
                }

                self.articles.insertContentsOf(items, at: 0)

            } catch {
                print("error fetchData")
            }
        }

        task.resume()
        self.tableView.reloadData()
    }

Is there a method i'm not aware of to handle this re-rendering? I've tried render methods for UITableViewCell like described here: setNeedsLayout and setNeedsDisplay

But there is no luck, can someone explain what is the best practice for rendering new records?

Best regards, Jos

Community
  • 1
  • 1
Jos Koomen
  • 372
  • 1
  • 3
  • 15

2 Answers2

3

@nwales is correct, though I would recommend getting familiar with property observers for reloading your data. Once your data is reloaded simply update your property and it will automatically fire your update.

 var data: [String] = [""] {
    didSet {
        // you could call a function or just reload right here      
        self.tableView.reloadData()
    }
 }

using @nwales method:

var data: [String] = [""] {
        didSet {      
             dispatch_async(dispatch_get_main_queue(),{
                 myTableView.reloadData()
             })
        }
}
Community
  • 1
  • 1
Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
2

After you've parsed the JSON try adding the following

 dispatch_async(dispatch_get_main_queue(),{
    myTableView.reloadData() //myTableView = your table view instance
 })
nwales
  • 3,521
  • 2
  • 25
  • 47
  • 1
    Adding an async dispatch was the correct way of doing this. This made me curious to find out more about why and when to use this kind of code: Through this comment i found a pretty good answer to get started: http://stackoverflow.com/a/12693409/575392 – Jos Koomen Dec 16 '15 at 19:36