我從服務器下載了一堆圖像文件,並且我希望確保只有在它們較新時才下載它們。 這種方法目前下載圖像就好了。但是,我不想浪費時間或精力在用戶每次登錄應用程序時重新下載圖像。相反,我只想下載任何文件A)不存在B)服務器上比在設備上更新iOS - 僅在修改時才下載文件(NSURL和NSData)
下面是我如何下載圖像: *圖像URL保存在覈心數據中與它關聯的視頻。 URL是使用一個簡單的換算方法,我建(generateThumbnailURL)
-(void)saveThumbnails{
NSManagedObjectContext *context = [self managedObjectContextThumbnails];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Videos" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
NSLog(@"Videos: %i",fetchedObjects.count);
if (fetchedObjects.count!=0) {
for(Videos *currentVideo in fetchedObjects){
// Get an image from the URL below
NSURL *thumbnailURL = [self generateThumbnailURL:[currentVideo.videoID intValue]];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:thumbnailURL]];
// Let's save the file into Document folder.
// You can also change this to your desktop for testing. (e.g. /Users/kiichi/Desktop/)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//Find Application's Document Directory
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"DownloadedThumbnails"];
// NSString *dataPath = @"/Users/macminidemo/Desktop/gt";//DEBUG SAVING IMAGE BY SAVING TO DESKTOP FOLDER
//Check if Sub-directory exists, if not, try to create it
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
NSError* error;
if([[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]){
NSLog(@"New Folder Created!");
}
else
{
NSLog(@"[%@] ERROR: attempting to write create new directory", [self class]);
NSAssert(FALSE, @"Failed to create directory maybe out of disk space?");
}
}
NSArray *splitFilename = [[self generateThumbnailFilename:[currentVideo.videoID intValue]] componentsSeparatedByString:@"."];//Break Filename Extension Off (not always PNGs)
NSString *subString = [splitFilename objectAtIndex:0];
NSString *formattedFilename = [NSString stringWithFormat:@"%@~ipad.png",subString];
NSString *localFilePath = [dataPath stringByAppendingPathComponent:formattedFilename];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
[imageData writeToFile:localFilePath atomically:YES];
NSLog(@"Image: %@ Saved!",formattedFilename);
}
}
}
感謝阿萊夫!我最終找到了從服務器檢測修改日期的另一種方法。但是你的方法可能是更好的處理方法。我現在要審查它。謝謝! – JimmyJammed
所以我只是嘗試了這種方法,但它每次都下載圖像。我的服務器啓用了緩存(CentOS上的apache)。 – JimmyJammed
不幸的是,這不起作用,因爲它沒有實現(從iOS 7.1開始)。在NSURLRequest.h中它被標記爲「NSURLRequestReloadRevalidatingCacheData = 5,//未實現」。 – Tricertops