Search code examples
iosnsdatansurlrequest

NSURLRequest returning nil


I am performing a simple download of data from a JSON service. When invoked the request returns a nil response object. This seems to be the same code I've used several times, but now I am stumped as to why the request returns nil. I have verified that the generated URL is valid and does return data. Am I missing something obvious? Thanks!

NSString *serviceEndpoint = [NSString stringWithFormat:@"http://waterservices.usgs.gov/nwis/iv/?sites=%@&period=PT%luH&format=json", guageID, hours];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceEndpoint]];

NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// response is nil at this point
NSDictionary *rvData = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonError];

Solution

  • You're totally disregarding the NSError and NSURLResponse that are also populated from the sendSynchronousRequest method.

    First, add a check to inquire whether the NSError has been populated (if the NSURLResponse if nil), and if it is not nil, you should inspect it to determine the problem of the request. You can also take a peak into the NSURLResponse object to also observe any properties to help debug the problem:

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL  URLWithString:@"http://waterservices.usgs.gov/nwis/iv/?sites=%@&period=PT%@luH&format=json", guageID, hours]];
    [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];
    if (responseData != nil)
    {
        NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
    }
    else
    {
       if (error != nil)
       {
           NSLog(@"Error description=%@", [err description]);
       }
    }