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 Photo Browser iPhone App Connecting to an API using OAuth Showing Photos in a Collection View

By calling dispach_async on the main queue, does that mean everything is run on the background thread?

In the video, we work on downloading the UIImage from instagram. Sam says we "move back to the main queue", where we set the photo to the uiimage within the dispatch_async get_main_queue block.

Does this mean the loading of the images, and other iOS methods are called in the background by default?

Thanks in advance!

Here is the full code:

NSURLSession *session = [NSURLSession sharedSession];
NSString *urlString = [[NSString alloc] initWithFormat:@"https://api.instagram.com/v1/tags/photobomb/media/recent?access_token=%@", self.accessToken];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

    NSData *data = [[NSData alloc] initWithContentsOfURL:location];
    NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    self.photos = [responseDictionary valueForKeyPath:@"data"];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView reloadData];
    });
}];
[task resume];

1 Answer

Michael Vilabrera
PLUS
Michael Vilabrera
Courses Plus Student 11,252 Points

They aren't moved to a background queue "by default". NSURLSessionDownloadTask moves that particular operation off the main queue, you call dispatch_async to bring the view method 'reloadData' back to the main queue

If we did not have NSURLSessionDownloadTask, the loading of images would make your app freeze.

check out iTunes U Stanford lecture #10 for a strongly detailed explanation