1
I implemented a json http request that works well, but it prevents the user from clicking by being able to access the information only when it is downloaded.
Example: I have a Uitableview with 3 Items, if I click one of them and this view is a request it will not enter the screen until it is ready.
Example of request class:
class Requisicao {
let urlDefault = "http://puc.vc/painel/webservice/"
func getJSON(urlToRequest: String) -> NSData{
let urlFull = urlDefault + urlToRequest
return NSData(contentsOfURL: NSURL(string: urlFull)!)!
}
func parseJSON(inputData: NSData) -> NSDictionary{
var error: NSError?
var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
return boardsDictionary
}
}
Example of the Call:
class ProcedAcadViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let request = Requisicao()
let data = request.getJSON("procedimentosacademicos/")
let json = request.parseJSON(data)
println(json)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
How can I solve this problem ?
Take a look at the comment on the right answer http://stackoverflow.com/questions/24065536/downloading-and-parsing-json-in-swift
– Gabriel Rodrigues
You asked why the request blocks events. This is because you perform the json download and Parsing operation on the main thread, which is responsible for handling events and rendering the UI. It is in this thread that the Uiviewcontroller lifecycle methods are called, such as viewDidLoad. To avoid this locking it is necessary to perform these operations outside the main thread.
– Rafael Leão
This dispatch_async must be executed in func viewDidLoad?
– Gabriel Rodrigues
It can be. There are actually several ways to do it. The important thing is not to do this kind of operation in the main thread. Otherwise it can crash the app and generate a bad user experience. Also, if the app depends on the request to continue browsing, it’s always good to show that it is processing something, for example using Mbprogresshud.
– Rafael Leão