我正在使用if-modified-since在HTTP标头中决定是否应该下载文件。
应用程序已经过测试,一切正常,但现在我在询问NSHTTPURLResponse实例response.statusCode
或[[response allHeaderFields] objectForKey:@"Last-Modified"]
时遇到错误。
似乎只是NSURLResponse。可能的原因是什么?
我读过this topic,但问题仍然不明确。 提前致谢! UPD: 一些代码:
NSURL *url = [NSURL URLWithString:urlString];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:url];
[myRequest setHTTPMethod:@"GET"];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'";
df.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[myRequest addValue:[df stringFromDate:lastModifiedLocal] forHTTPHeaderField:@"If-Modified-Since"];
myRequest.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
NSHTTPURLResponse *response=nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) {
NSLog(@"Error sending request: %@", [error localizedDescription]);
}
//As was advised
NSHTTPURLResponse* newResp = (NSHTTPURLResponse*)response;
//crash here
NSLog(@"%d", newResp.statusCode);
UPD: 代码错误 - myRequest和request是不同的变量。问题解决了。
答案 0 :(得分:3)
请求很可能失败,并且没有生成响应对象。您可以按如下方式检查:
if (response) {
NSHTTPURLResponse* newResp = (NSHTTPURLResponse*)response;
NSLog(@"%d", newResp.statusCode);
}
else {
NSLog(@"No response received");
}
正如另一位评论者所建议的那样,您应该包含一个NSError对象,以便更有效地检查错误:
NSHTTPURLResponse *response=nil;
NSError *error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: &error];
然后,您可以在检查响应之前检查错误:
if (error) {
NSLog(@"Error sending request: %@", [error localizedDescription]);
}
答案 1 :(得分:0)
你可以简单地施展它:
- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)aResponse
{
self.response = (NSHTTPURLResponse *)aResponse;
}
修改强>
您的回复是NULL。试试这个:
NSHTTPURLResponse *response = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];