0

I am having some trouble with my app parsing the JSON from PHP. What I do, is echo (JSON_Encoded) an array on PHP and when I use the url, it returns the JSON format on the browser.

The problem is that when I try to parse it, the app crashes saying that the data is null.

This is the url I am using (PHP):

http://iamitman.com/interdev/ScanAPP/asist.php?EvtGN=3500&VistGN=500

And this is the code to parse it:

    // Download JSON
    NSData *JSONData = [NSData dataWithContentsOfURL:[NSURL URLWithString:theURL]];
    NSLog(@"%@",JSONData);
    // Parse JSON
    NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
    self.data = jsonResult;
    NSMutableArray *_names = [NSMutableArray array];
    for (id item in jsonResult)
        [_names addObject:[NSString stringWithFormat:@"%@ %@", item[@"Name"], item[@"Last"]]];
    self.names = _names;

The app crashes with this error code:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'

Yet, if I use this url (JSON format, txt), the code works fine:

https://raw.githubusercontent.com/VinceG/Auto-Cars-Makes-And-Models/master/models-json.txt

The difference is that is a .txt file in JSON format.

Why is the app crashing then? Any tips?

Thank you!

Michael Ortiz
  • 732
  • 1
  • 7
  • 20
  • The `Content-Type` in the response headers from the iamitman site is "text/html", where the other one is "text/plain". Perhaps if you set it to use a JSON specific content type like "application/json" it will work? http://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type – Jeremy Harris Dec 18 '15 at 02:09
  • This change has to be done on the server or I have to do it on the app itself? – Michael Ortiz Dec 18 '15 at 02:58
  • On the server running PHP. You can use the PHP `header()` function to set the content type – Jeremy Harris Dec 18 '15 at 02:59
  • ok! I will give that a try! I'll let you know if that works. – Michael Ortiz Dec 18 '15 at 03:01

0 Answers0