我一直試圖保存和加載UIImages在我的應用程序的文檔文件夾或最好是臨時文件夾(所以每次我的應用程序被關閉的圖像將被刪除),但他們不能正常工作。我已經嘗試了三種方法,但只有第三種方法有效,我想知道什麼是正確的方法?我非常感謝任何幫助。爲什麼在iOS 8+中無法正常保存和加載UIImages文檔文件夾?
//First Approach, to save and load later, Doesn't work.
//Saving the image
NSURL *documentsDirectoryURL = [[[NSFileManager defaultManager]
URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask]
lastObject];
NSString*fileDirectoryStr = [[documentsDirectoryURL path] stringByAppendingPathComponent:@"E1BG.png"];
NSURL *url = [NSURL URLWithString:fileDirectoryStr];
//Saving either as Jpeg
[UIImagePNGRepresentation(finalFG) writeToFile:fileDirectoryStr atomically:YES];
//Or as PNG, because I need the transparent part to be kept transparent but non of them work.
[UIImageJPEGRepresentation(finalFG, 1.0) writeToFile:fileDirectoryStr atomically:YES];
//Loading image
UIImage *loadedBGImg = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
//Returns nil
//Second approach.
//Saving the image
NSArray*pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsPath = [pathArray objectAtIndex:0];
NSString* fileDirectoryStr = [documentsPath stringByAppendingPathComponent:@"E1FG.png"];
//Again saving either as Jpeg
[UIImagePNGRepresentation(finalFG) writeToFile:fileDirectoryStr atomically:YES];
//Or as PNG, because I need the transparent part to be kept transparent but non of them work.
[UIImageJPEGRepresentation(finalFG, 1.0) writeToFile:fileDirectoryStr atomically:YES];
NSURL *url1 = [NSURL URLWithString:fileDirectoryStr];
//Loading image
UIImage *loadedImg = [UIImage imageWithData: [NSData dataWithContentsOfURL:url1]];
//Third approach, Works but doesnt seem to be very efficient.
NSString *tmpDirectory = NSTemporaryDirectory();
//Save
NSString *tmpFileStrFG = [tmpDirectory stringByAppendingPathComponent:@"E1FG.png"];
NSURL *urlFG = [NSURL URLWithString:tmpFileStrFG];
NSData *imgDataFG = UIImagePNGRepresentation(finalFG);
[imgDataFG writeToURL:urlFG atomically:YES];
//Load
UIImage *ImggFG = [UIImage imageWithData: imgDataFG];
你想保存和文件目錄檢索圖像。這是你的問題正確嗎? –
不,我的意思是爲什麼前兩種方法不起作用?我究竟做錯了什麼?我是否正確地使用第三種方法在我的應用程序中使用臨時文件夾來做到這一點? @MikeAlter –
保存方法二看起來不錯。請檢查提取url加載圖像,我不知道有關方法 –