我正在执行来自JSON服务的数据的简单下载。调用该请求时,将返回一个nil响应对象。这似乎与我多次使用的代码相同,但现在我很困惑为什么请求返回为零。我已经验证了生成的URL是有效的,并且确实返回数据。我漏掉了什么明显的东西吗?谢谢!
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];发布于 2014-10-31 12:41:15
您完全忽略了NSError和NSURLResponse,它们也是从sendSynchronousRequest方法中填充的。
首先,添加一个检查以询问是否填充了NSError (如果NSURLResponse为零),如果不是零,则应该检查它以确定请求的问题。您还可以在NSURLResponse对象中设置一个峰值,以观察帮助调试问题的任何属性:
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]);
}
}https://stackoverflow.com/questions/26674775
复制相似问题