我的代码的目的是比较服务器文件和本地文件的修改日期,以防服务器文件较新,它将下载该文件。
我的第一次尝试是使用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)
返回(空)。PS:如果有更好的方法可以解释自己或代码,请告诉我。
更新
我使用的URL的类型为
ftp://
,这可能是为什么我没有得到任何HEADERS的问题。但是我不知道该怎么做。 最佳答案
将您的代码更改为此...在“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]
}