在我的 iPhone 应用程序中,我需要通过 查询 Internet.m4a文件的最后修改日期HTTP,但我不想下载它。
我正在阅读 Apple 关于NSURLRequestand的文档NSHTTPURLResponse,但它似乎都与下载文件而不是先查询它有关。也许我错了。
我如何知道.m4a文件的最后修改日期,通过HTTP,而不下载它?
谢谢!
在我的 iPhone 应用程序中,我需要通过 查询 Internet.m4a文件的最后修改日期HTTP,但我不想下载它。
我正在阅读 Apple 关于NSURLRequestand的文档NSHTTPURLResponse,但它似乎都与下载文件而不是先查询它有关。也许我错了。
我如何知道.m4a文件的最后修改日期,通过HTTP,而不下载它?
谢谢!
此答案假定您的服务器支持它,但您所做的是将“HEAD”请求发送到文件 URL,然后您只返回文件头。然后,您可以检查名为“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.
});
});
我在这里写了一篇关于这个的文章: