我正在使用如果-修改-自在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和请求是不同的变量.问题解决了。
发布于 2012-01-17 16:23:51
很可能请求失败了,并且没有生成响应对象。您可以按以下方式进行检查:
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]);
}发布于 2012-01-17 10:03:54
你可以简单的投出它:
- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)aResponse
{
self.response = (NSHTTPURLResponse *)aResponse;
}编辑
你的反应无效。试试这个:
NSHTTPURLResponse *response = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; https://stackoverflow.com/questions/8892638
复制相似问题