Search code examples
objective-cjsonnsstringnsscanner

Using Objective-c to parse information from JSON url


I'm trying to write a piece of code that will make use of reddits JSON format. I intend to visit the url: http://www.reddit.com/r/pics/new/.json, search for the string: "title": " and write everything from there till the next apostrophe " to the log, continuing until all titles have been written to the log.

So far I have this, but I am not getting any log output. Can anybody help me?

- (void)viewDidLoad
{
    NSString *redditString = @"http://www.reddit.com/r/pics/new/.json";
    NSURL *redditURL = [NSURL URLWithString:redditString];
    NSError *error;
    NSCharacterSet *commaSet;
    NSScanner *theScanner;
    NSMutableString *jsonText = [[NSMutableString alloc] init];
    NSString *TITLE = @"\"title\": \"";
    NSString *postTitle;
    commaSet = [NSCharacterSet characterSetWithCharactersInString:@"\""];
    theScanner = [NSScanner scannerWithString:jsonText];
    [jsonText appendString:[NSString stringWithContentsOfURL:redditURL encoding:NSASCIIStringEncoding error:&error]];
    if ([theScanner scanString:TITLE intoString:NULL] && [theScanner scanUpToCharactersFromSet:commaSet intoString:&postTitle] && [theScanner scanString:@"\"" intoString:NULL]) {
             NSLog(@"%@", postTitle);
    }
}

Oh, and this all builds with no errors, but that's no surprise.

Thanks very much for your help, all tips, corrections, or anything else very much appreciated.


Solution

  • NSScanner is the wrong tool for the job. You'd better use a JSON (de)serializer, such as NSJSONSerialization, instead.

    To make your life even easier you can take advantage of AFNetworking, a networking framework which supports JSON requests. Your code would reduce to something like

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://www.reddit.com/r/pics/new/.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *entries = responseObject[@"data"][@"children"];
        for (NSDictionary *entry in entries) {
            NSLog(@"%@", entry[@"title"]);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];