"Build a Selfie App with Swift 2" was retired on May 31, 2020.

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

Loading JSON asynchronously (BlogReader app)

Using the BlogReader app as a starting point, how can I load the JSOn asynchronously?

NSURL *blogURL = [NSURL URLWithString:@"http://blog.teamtreehouse.com/api/get_recent_summary/"];

NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];

NSError *error = nil;

NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
//    NSLog(@"%@",dataDictionary);

self.blogPosts = [NSMutableArray array];

NSArray *blogPostsArray = [dataDictionary objectForKey:@"posts"];

for (NSDictionary *bpDictionary in blogPostsArray) {
    BlogPost *blogPost = [BlogPost blogPostWithTitle:[bpDictionary objectForKey:@"title"]];
    blogPost.author = [bpDictionary objectForKey:@"author"];
    blogPost.thumbnail = [bpDictionary objectForKey:@"thumbnail"];
    blogPost.date = [bpDictionary objectForKey:@"date"];
    blogPost.url = [NSURL URLWithString:[bpDictionary objectForKey:@"url"]];
    [self.blogPosts addObject:blogPost];
}

Also is the viewDidLoad the best place to load the JSON or should I put it somewhere else?

Thanks.

1 Answer

Thanks, I'll check it out.