3

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

我的第一次尝试是使用来自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:如果有更好的方法可以解释自己或代码,请告诉我。

更新

我使用的 URL 是类型的ftp://,这可能是我没有得到任何 HEADERS 的问题。但我不知道该怎么做。

4

1 回答 1

3

将您的代码更改为此...在“如果”条件下,您正在检查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]
}
于 2012-11-21T23:32:18.037 回答