1

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()

1 Answer 1

1

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()){...}.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.