Reputation: 2324
I'm tried to problems doing http-request, because I can hardly understand all about sync and async methods. I just want to know how can I make compiler wait for started http-request finishing and only then continue executig?
For example, I need to get some page, parse data and post it to another. But when request which posts data parsed from first request executes first and only then request which parses data executing - I've a big butthurt.
Upvotes: 0
Views: 205
Reputation: 5122
You should avoid synchronous network requests as a plague. It has two main problems:
I'd suggest you to use some well-written libraries for network requests, like Alamofire or AFNetworking. For Swift and what you are trying to accomplish I'd recommend Alamofire, as it is FAR more easier to use and covers all the basic stuff you need.
You can perform basic requests like this:
// Perform GET request
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["key": "value"])
.response { request, response, data, error in
// Do something with response or error
println(response)
println(error)
}
Now, as for your question, you can always block UI until the network operation is completed, be it by postponing performSegue, or simply disallowing "Next" button until you get response, OR simply by overlaying view with progress bar / spinner, for example using SVProgressHUD library. Combined all together, you can do it like this:
// Show progress HUD. This disables user interaction by default
SVProgressHUD.show()
// Perform GET request
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["key": "value"])
.response { request, response, data, error in
// Do something with response or error
println(response)
println(error)
// Hide progress to enable user interaction again
SVProgressHUD.dismiss()
// Or optionally perform transition to different controller here
self.performSegueWithIdentifier(identifier, sender: nil)
}
Hope it helps!
Upvotes: 1