EyeQ Tech
EyeQ Tech

Reputation: 7358

iOS: dispatch_async( dispatch_get_main_queue())

Pardon me for beginner's question. I'm following a tutorial, it has the following snippet. I don't understand the point of dispatch_async, if you execute the block self.webView... on the main queue on the main thread by calling dispatch_get_main_queue() anyway, why bother putting it inside dispatch_async?
Thanks

let url = NSURL(string: "http://www.stackoverflow.com")

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
        (data, response, error) in

        if error == nil {

            var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding)

            println(urlContent)

            dispatch_async(dispatch_get_main_queue()) {

                self.webView.loadHTMLString(urlContent!, baseURL: nil)

            }

        }


    }

    task.resume()

Upvotes: 1

Views: 1495

Answers (1)

ramacode
ramacode

Reputation: 924

dispatch_async is used to execute block on the other queue. It needs 2 parameters, first is the queue that it should execute in, second the code block.

NSURLSession.sharedSession().dataTaskWithURL(url!){...}

The reason why they use dispatch_async in your code is that the ... code block will be executed in other queue (not in the main queue).

So if you want to execute self.webView.loadHTMLString(urlContent!, baseURL: nil) in the main queue, then you have to use dispatch_async(dispatch_get_main_queue()){...}.

Upvotes: 1

Related Questions