0
votes

I was developing apps using web services when I run the application it got responses but some time its crashes and show error like this:

NSInvalidArgumentException', reason: 'data parameter is nil'

Here is my coding:

NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://api.espn.com/v1/sports/tennis/news/headlines?apikey=th98vzm67pufc36ka42xxxmy"]];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];

NSError *err;
NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *jsonArray=[NSJSONSerialization JSONObjectWithData:responseData  options:NSJSONReadingMutableContainers error:&err];
NSArray *headlinetop=[jsonArray objectForKey:@"headlines"];

for (int i=0; i<[headlinetop count]; i++)
{
    NSString *headstr=[[headlinetop objectAtIndex:i]objectForKey:@"headline"];
    [loadingcell addObject:headstr];
}
3
And what about logging responseData, err...? Is data nil for only one URL?Larme
i got response well but some time it crashes like thisuser3767326
Well, when it crash, checking the err could be interesting. And I'd use a other NSError than using twice err. Not checking them, is like putting nil instead.Larme

3 Answers

2
votes

I suspect the "headline" object isn't always available; guard against that using:

for (int i=0; i<[headlinetop count]; i++)
{
    NSString *headstr=[[headlinetop objectAtIndex:i]objectForKey:@"headline"];
    if (headstr)
        [loadingcell addObject:headstr];
}

If loadcell is an Objective-C collection class, it will object to headstr being nil as they cannot store NULL objects.

2
votes

The problem is this code:

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *jsonArray=[NSJSONSerialization JSONObjectWithData:responseData  options:NSJSONReadingMutableContainers error:&err];

Sending a URL request you should always expect that something went wrong. There are many reasons for it. In this case responseData is nil. NSJSONSerialization expects the data arg not to be nil: Error.

When receiving a response for a request you should always check it for being nil. Always.

So the code should look like this:

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
if (responseData == nil)
{
  //  Maybe logging. But getting nil as a response of a URL request isn't exciting.
  return; // or whatever you have to (not) do
}
NSDictionary *jsonArray=[NSJSONSerialization JSONObjectWithData:responseData  options:NSJSONReadingMutableContainers error:&err];
0
votes

I think your problem is Url which you are using. Please check the following link: 'NSInvalidArgumentException', reason: 'data parameter is nil'