Reputation: 25
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];
}
Upvotes: 0
Views: 9437
Reputation: 16660
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];
Upvotes: 2
Reputation: 1267
I think your problem is Url which you are using. Please check the following link: 'NSInvalidArgumentException', reason: 'data parameter is nil'
Upvotes: 0
Reputation: 122401
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.
Upvotes: 2