为什么在文档文件夹中保存和加载 UIImages 在 iOS 8+ 中不能正常工作?

Why saving and loading UIImages in documents folder doesn't work properly in 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];

在读取文件之前,请确保它存在于那里。如果确实存在,则问题出在 [NSData dataWithContentsOfURL:url] 否则图像未转换为数据。

我建议,将您的代码分成几条语句,而不是编写一个冗长的语句,以便更好地理解它在哪里失败。

我创建了 class 允许保存在文件夹中

这是.h文件

@interface FileUtility : NSObject {

}

// Folder methods
+ (NSString*)basePath;
+ (void)createFile:(NSString *)filename;
+ (void)createFile:(NSString *)filePath withData: (NSData *) imgData;

@end

和 .m 文件

#import "FileUtility.h"

@implementation FileUtility

// ----------------------------------------------------------------------------

#pragma mark -
#pragma mark Path methods

// -----------------------------------------------------------------------------

+ (NSString*)basePath {
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSAssert([paths count] == 1, @"");
    return [paths objectAtIndex:0];     
}

// -----------------------------------------------------------------------------




  + (void)createFile:(NSString *)filename {
    NSFileManager* manager = [NSFileManager defaultManager];
    NSString * filePath = [NSString stringWithFormat:@"%@/%@", [FileUtility basePath],filename];
    DLOG(@"filePath = %@", filePath);
    if (![FileUtility fileExists:filePath]){
        [manager createFileAtPath:filePath contents:nil attributes:nil];
    }

    }

// -----------------------------------------------------------------------------

+ (void)createFile:(NSString *)filePath withData: (NSData *) imgData {
    NSFileManager* manager = [NSFileManager defaultManager];
    DLOG(@"filePath = %@", filePath);
    if (![FileUtility fileExists:filePath]){
        [manager createFileAtPath:filePath contents:imgData attributes:nil];
    }
}

获取使用这个

[[FileUtility basePath] stringByAppendingPathComponent

编辑

+ (BOOL)fileExists:(NSString *)filename {
    NSFileManager* manager = [NSFileManager defaultManager];
    return [manager fileExistsAtPath:filename];
}