Reputation: 11
I am new to iOS development and need help on below issue. I have the below code that downloads a JSON data from web and populates an array with that.
let urlPath = "……………………………"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
if (error != nil) {
println(error)
} else {
let jsonResult: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)!
dispatch_async(dispatch_get_main_queue()) {
for var i = 0; i < jsonResult.count; i++ {
self.sales[i] = jsonResult[i]["daily_sales"] as NSString
}
}
}
})
task.resume()
println(self.sales[0])
at the end the app crashes since it does not wait for the JSON data to be downloaded.
What are the alternative ways to handle this?
Upvotes: 0
Views: 81
Reputation: 3991
It crashes because of this println(self.sales[0])
. You trying to display sales that are not even downloaded. Put this line at the end of your completion block and you should be OK
Upvotes: 1