8

I am trying to parse JSON for an ios 6 app, but can't seem to get it to work. I have scoured tons of forums but haven't found a solution that works, that I understand enough to implement, or that applies.

I apologize if there is one that I missed.

First I have a test WebService that as far as I can tell returns valid JSON

http://thetrouthunter.com/SVLocationsAPI.php

Second, here is my Objective-C code:

+ (NSDictionary *)connectToService:(NSString *)query
{
    NSError *error = nil;

    query = [NSString stringWithFormat:@"%@&format=json&nojsoncallback=1", query];
    query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error] : nil;

    NSLog(@"locations: %@", results);

    if (error)
        NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);

    return results;
}

+ (NSArray *)userLocation {
    NSString *request = [NSString stringWithFormat:@"http://thetrouthunter.com/SVLocationsAPI.php"];
    return [[self connectToService:request] valueForKeyPath:@"locations.location"];
}

The ls NSLog function is printing out the error: "The operation couldn't be completed. (Cocoa error: 3840.)"

I can't figure out why this is the case. I have tried all sorts of things.

WrightsCS
  • 50,551
  • 22
  • 134
  • 186
dherrin79
  • 367
  • 1
  • 4
  • 13

1 Answers1

4

You are adding %@&format=json&nojsoncallback=1 to the URL in connectToService:, and that new URL results in a webpage, not the JSON you expect (i.e. http://thetrouthunter.com/SVLocationsAPI.php&format=json&nojsoncallback=1).

It might be useful to log the actual result from the HTTP request so that you can debug this until you get JSON (i.e. prior to calling the serialization functions).

abellina
  • 1,016
  • 1
  • 11
  • 27
  • Great that worked .THANKS! But when I am ready to start adding parameters via query string how would I do that? – dherrin79 Mar 20 '13 at 20:50
  • You can add parameters to the URL, just make sure the output of your script is JSON :) – abellina Mar 20 '13 at 20:55
  • I see. I didn't even realize that my site was redirecting to the home page when the query string was applied. Thanks for your help and super quick reply. – dherrin79 Mar 20 '13 at 20:59