Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Weather App with Swift Interacting with Data From the Web Writing Concurrent Networking Code

Jakub Lares
Jakub Lares
6,469 Points

Mistake in showing how threads works

Hi, I think, you have mistake in showing, how threads works. Your code looks like this (it's Xcode 7 syntax) :

    let dataTask = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        print(data!)
        print("I'am on a background thread")
    }

    print("I'am on the main thread!")
    dataTask.resume()

and you are saying, "Iam on the main thread is showing first, even if iam on a background thread is first in code." Thats right, but you are starting dataTask with dataTask.resume() and that is after Iam on the main thread print. Your code should look like this:

    let dataTask = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        print(data!)
        print("I'am on a background thread")
    }

    dataTask.resume()
    print("I'am on the main thread!")

but its not change, how prints are printed. Iam on the main thread is first and Iam on a background thread is second. But if you write it like this, its proof, that system create another thread and there is running dataTask and in main thread code is continue by printing Iam on the main thread. dataTask takes a bit time to get information back by API and thats why Iam on a background thread is printed later even if its called sooner than Iam on the main thread print.