I am having difficulty displaying a progressHUD properly when parsing JSON using SwiftyJSON as the app seems to crash if I do not wait a few seconds even after showing the progressHUD.
It will not crash if I wait a few seconds after the progress bar disappears which means I must be doing something wrong with the dispatch async queue. I am unsure of where is the completion handler for SwiftyJSON after parsing the API.
The cause of the crash is that the array index is out of range as my data is not loaded properly yet.
override func viewDidLoad() {
super.viewDidLoad()
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
dispatch_async(dispatch_get_main_queue()) {
self.parseAPI()
MBProgressHUD.hideHUDForView(self.view, animated: true)
self.myTable.reloadData()
}
}
func parseAPI() {
let url = NSURL(string: "https://www.kimonolabs.com/api/e0uyfycg?apikey=7v9FHVAWKgAspMtVwoTNvIwzmWiPyj0F")
let dataFromNetwork = NSData(contentsOfURL: url!)
let json = JSON(data: dataFromNetwork!)
}
You should parse the API in a background thread, otherwise it will parse on the main thread and block the UI until it's finished.
I've had a look at the MBProgressHUD page and it seems to work like this:
override func viewDidLoad() {
super.viewDidLoad()
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0)) {
self.parseAPI()
dispatch_async(dispatch_get_main_queue()) {
MBProgressHUD.hideHUDForView(self.view, animated: true)
self.myTable.reloadData()
}
}
}