0
votes

I'm trying to write an HTTP request using Swift and I really only see people going one way or another (actually not so much GCD) to do HTTP requests on iOS.

If I want to make an HTTP request in iOS, what would be the best way to go about it: Use Grand Central Dispatch or write some closure block? Also, where can I find some great examples. From what I read online, I'm having a hard time seeing the benefits of one over the other.

At the moment, I have this code:

    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT

    dispatch_async(dispatch_get_global_queue(priority, 0), { ()->() in

        self.activityIndicator.startAnimating()
        self.authenticateUser()

        dispatch_async(dispatch_get_main_queue(), {
            self.activityIndicator.stopAnimating()
        })
    })

From what I see in the Debug Session tab for the Processor, I can see it jump from Thread X to Thread Y (for authenticateUser) and back to Thread X. Which is good - this is what I want (I'm sure).

Any good examples of GCD or Blocks/Closures written in Swift that you might be aware of would be very handy too. Thanks!

2
GCD uses closures. You can't use GCD in Swift without using closures. Anyway, have you looked at the URL Loading System Programming Guide?rob mayoff
@MaximShoustin is this better than using GCD or a more "Correct Way" of doing async http requests?Mario A Guzman
Using blocks + dispatch_async VS. NSURLSession: teamtreehouse.com/forum/…. For ios7+ i would use NSURLSession. For backwards compatibility - GCDMaxim Shoustin

2 Answers

3
votes

Use NSURLSession to make your HTTP request. Use GCD to implement concurrency in your app (multiple things happening at the same time). And use Closures to give a structure to your application. As you can see now, all of them can be used at the same time.

By the way, always remember this: All UI modifications must be called in the main thread, in your code you are calling this self.activityIndicator.startAnimating() on a concurrent queue.

1
votes

You can use NSURLSession. Basic usage is like

NSURLSession.sharedSession().dataTaskWithRequest(request) { data, urlResponse, error in
    // handle the response
}.resume()