SwiftStudier
SwiftStudier

Reputation: 2324

Sending http-request in swift

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

Answers (1)

Jiri Trecak
Jiri Trecak

Reputation: 5122

You should avoid synchronous network requests as a plague. It has two main problems:

  • The request blocks your UI if not called from different thread which is big no-no for great quality application (well, for any application really)
  • There is no way how to cancel that request except when it errors on its own

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

Related Questions