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

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

我正在阅读关于NSURLRequestNSHTTPURLResponse Apple文档,但它似乎都与下载文件有关,而不是先查询它。 也许我错了。

如何通过HTTP知道.m4a文件的最后修改日期, 无需下载?

谢谢!

这个答案假定您的服务器支持它,但您所做的是向文件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"); } 

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

最好的祝福。

下面的方法执行HEAD请求,仅获取具有Last-Modified字段的标头,并将其转换为NSDate对象。

 - (NSDate *)lastModificationDateOfFileAtURL:(NSURL *)url { NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; // Set the HTTP method to HEAD to only get the header. request.HTTPMethod = @"HEAD"; NSHTTPURLResponse *response = nil; NSError *error = nil; [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (error) { NSLog(@"Error: %@", error.localizedDescription); return nil; } else if([response respondsToSelector:@selector(allHeaderFields)]) { NSDictionary *headerFields = [response allHeaderFields]; NSString *lastModification = [headerFields objectForKey:@"Last-Modified"]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss zzz"]; return [formatter dateFromString:lastModification]; } return nil; } 

您应该在后台异步运行此方法,以便不阻止主线程等待响应。 这可以使用几行GCD轻松完成。

下面的代码执行调用以获取后台线程中的最后修改日期,并在检索日期时调用主线程上的完成块。

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ { // Perform a call on the background thread. NSURL *url = [NSURL URLWithString:@"yourFileURL"]; NSDate *lastModifDate = [self lastModificationDateOfFileAtURL:url]; dispatch_async(dispatch_get_main_queue(), ^ { // Do stuff with lastModifDate on the main thread. }); }); 

我在这里写了一篇关于此的文章:

使用Objective-C获取服务器上文件的最后修改日期。