The following method executes a HEAD
request only to get the header with the Last-Modified
field and converts it to an NSDate
object.
- (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; }
You must run this method asynchronously in the background so that the main thread does not block while waiting for a response. This can be easily done using a couple of GCD
lines.
The code below makes a call to get the latest change date in the background thread and calls the completion block in the main thread when it receives the date.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
I wrote an article about this here:
Getting the latest modification date of a file on the server using Objective-C.
source share