如何使用NSHTTPURLResponse在iPhone上通过HTTP查询文件的最后修改日期?

Win*_*ton 6 iphone cocoa-touch objective-c nsurlrequest ios

在我的iPhone应用程序,我需要查询互联网的最后修改日期.m4a通过文件HTTP,但我不要想下载它.

我读苹果文档中关于NSURLRequestNSHTTPURLResponse的,但它似乎是所有与下载文件,而不是首先查询它.也许我错了.

我怎么能知道的最后修改日期.m4a的文件,通过HTTP,下载呢?

谢谢!

Mat*_*ong 9

这个答案假定您的服务器支持它,但您所做的是向文件URL发送"HEAD"请求,然后您只返回文件头.然后,您可以检查名为"Last-Modified"的标头,该标头通常具有日期格式@"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'".

这是一些代码:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"HEAD"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if ([response respondsToSelector:@selector(allHeaderFields)]) 
{
  NSDictionary *dictionary = [response allHeaderFields];
  NSString *lastUpdated = [dictionary valueForKey:@"Last-Modified"];
  NSDate *lastUpdatedServer = [fileDateFormatter dateFromString:lastUpdated];

  if (([localCreateDate earlierDate:lastUpdatedServer] == localCreateDate) && lastUpdatedServer) 
  {
    NSLog(@"local file is outdated: %@ ", localPath);
    isLatest = NO;
  } else {
    NSLog(@"local file is current: %@ ", localPath);
  }

} else {
  NSLog(@"Failed to get server response headers");
}
Run Code Online (Sandbox Code Playgroud)

当然,您可能希望在后台异步完成此操作,但此代码应指向正确的方向.

最好的祝福.