如何使用NSHTTPURLResponse在iPhone上通过HTTP查询文件的最后修改日期?
在我的iPhone应用程序中,我需要通过HTTP
查询互联网.m4a
文件的最后修改日期,但我不想下载它。
我正在阅读关于NSURLRequest
和NSHTTPURLResponse
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获取服务器上文件的最后修改日期。
- 在使用OpenInfunction的应用程序中,无法通过webbrowser打开docx文件
- 如何在iPhone应用程序中获取带有两个小数位的String
- self.navigationController pushViewController无法正常工作
- XCode中的组和文件与Finder中的项目文件夹
- 通过UINavigationController错误向后导航
- 如何制作一个半边圆angular(顶angular圆angular)texview带边框?
- UITextFieldDelegate问题
- 将kABPersonPhoneProperty转换为阿拉伯数字
- iOS 5.0.1:如何validation文件夹被标记为“不备份”iCloud?