HEADER请求allHeaderFields无效

时间:2012-11-21 23:09:58

标签: ios asynchronous header request synchronous

我的代码的目的是比较服务器文件和本地文件的修改日期,如果服务器文件较新,它将下载它。

我的第一次尝试是使用http://iphoneincubator.com/blog/server-communication/how-to-download-a-file-only-if-it-has-been-updated

中的代码来使用同步请求

但它没有奏效。 之后我一直在努力寻找解决方案,尝试异步请求,尝试了我在stackoverflow,google等周围找到的不同代码,但没有任何作用。

如果在终端我做curl -I <url-to-file>我得到标题值,所以我知道这不是服务器问题。

这是我现在正在努力的代码(它是用Appdelegate.m编写的)

- (void)downloadFileIfUpdated {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
                                                       cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
                                                   timeoutInterval: 10];
[request setHTTPMethod:@"HEAD"];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
  if(!connection) {
    NSLog(@"connection failed");
  } else {
    NSLog(@"connection succeeded");
  }
}



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self downloadFileIfUpdated]
}



#pragma mark NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSString *lastModifiedString = nil;
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  if ([response respondsToSelector:@selector(allHeaderFields)]) {
    lastModifiedString = [[response allHeaderFields] objectForKey:@"Last-Modified"];
  }
  [Here is where the formatting-date-code and downloading would take place]
}

现在,事实上,它给了我错误No visible @interface for 'NSURLResponse' declares de selector 'allHeaderFields'

当我使用同步方法时,错误是NSLog(@"%@",lastModifiedString)返回(null)。

PS:如果有更好的方式我可以解释自己或代码,请告诉我。

更新

我使用的网址是ftp://类型,这可能是我没有获得任何标题的问题。但我无法弄清楚如何做到这一点。

1 个答案:

答案 0 :(得分:3)

将您的代码更改为此...在“if”条件中,您检查的是response而不是httpResponse

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSString *lastModifiedString = nil;
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  if ([httpResponse respondsToSelector:@selector(allHeaderFields)]) {
    lastModifiedString = [[httpResponse allHeaderFields] objectForKey:@"Last-Modified"];
  }
  // [Here is where the formatting-date-code and downloading would take place]
}

...一旦你觉得响应永远是NSHTTPURLResponse,你可能只是摆脱了条件语句:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  NSString *lastModifiedString = [[httpResponse allHeaderFields] objectForKey:@"Last-Modified"];
  // [Here is where the formatting-date-code and downloading would take place]
}