I am downloading a bunch of image files from a server, and I want to ensure that they are downloaded only if they are newer. This method currently downloads the images just
If your server supports HTTP caching you can specify you want cached content with NSURLRequestReloadRevalidatingCacheData
:
NSURLRequest* request = [NSURLRequest requestWithURL:thumbnailURL cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:20];
NSURLResponse* response;
NSError* error;
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
UIImage* image = [UIImage imageWithData:data];
For more info read the NSURLRequest documentation.
I ended up using this method to detect the modified date on the file: *Found on HERE
-(bool)isThumbnailModified:(NSURL *)thumbnailURL forFile:(NSString *)thumbnailFilePath{
// create a HTTP request to get the file information from the web server
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:thumbnailURL];
[request setHTTPMethod:@"HEAD"];
NSHTTPURLResponse* response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
// get the last modified info from the HTTP header
NSString* httpLastModified = nil;
if ([response respondsToSelector:@selector(allHeaderFields)])
{
httpLastModified = [[response allHeaderFields]
objectForKey:@"Last-Modified"];
}
// setup a date formatter to query the server file's modified date
// don't ask me about this part of the code ... it works, that's all I know :)
NSDateFormatter* df = [[NSDateFormatter alloc] init];
df.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'";
df.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
// get the file attributes to retrieve the local file's modified date
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDictionary* fileAttributes = [fileManager attributesOfItemAtPath:thumbnailFilePath error:nil];
// test if the server file's date is later than the local file's date
NSDate* serverFileDate = [df dateFromString:httpLastModified];
NSDate* localFileDate = [fileAttributes fileModificationDate];
NSLog(@"Local File Date: %@ Server File Date: %@",localFileDate,serverFileDate);
//If file doesn't exist, download it
if(localFileDate==nil){
return YES;
}
return ([localFileDate laterDate:serverFileDate] == serverFileDate);
}