I\'m attempting to learn Swift
& the basics of iOS
dev at the same time, so bear with me. I\'ve got a TableViewController
that is
All the calls to UI should be asynchronous, anything you change on the UI like updating table or changing text label should be done from main thread. using DispatchQueue.main will add your operation to the queue on the main thread.
Swift 4
DispatchQueue.main.async{
self.tableView.reloadData()
}
I was also facing the same issue, what I did wrong was that I'd forgot to add
tableView.delegate = self
tableView.dataSource = self
in the viewDidLoad() {} method. This could be one reason of self.tableView.reloadData() not working.
If your connection is in background thread then you should update UI in main thread like this
self.tblMainTable.performSelectorOnMainThread(Selector("reloadData"), withObject: nil, waitUntilDone: true)
As I have mentioned here
Swift 4:
self.tblMainTable.performSelector(onMainThread: #selector(UICollectionView.reloadData), with: nil, waitUntilDone: true)
You'll need to reload the table on the UI
thread via:
//swift 2.3
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
//swift 5
DispatchQueue.main.async{
self.tableView.reloadData()
}
Follow up:
An easier alternative to the connection.start()
approach is to instead use NSURLConnection.sendAsynchronousRequest(...)
//NSOperationQueue.mainQueue() is the main thread
NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: url), queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
//check error
var jsonError: NSError?
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &jsonError)
//check jsonError
self.collectionView?.reloadData()
}
This doesn't allow you the flexibility of tracking the bytes though, for example you might want to calculate the progress of the download via bytesDownloaded/bytesNeeded