iOS 缓存文件到沙盒目录的执行文件夹下,并再次读取文件

2018-06-14  本文已影响0人  王_哪跑

开发中我们经常要将一些文件缓存到沙盒路径下,并且把指定的类型储存到指定文件夹下,以便于方便管理。

下面是以图片为例

首先显示缓存到指定文件夹下,注释解释很详细

/**

将图片存储到沙盒目录下存储成jpg形式,可以将图片保存成不通的格式类型、png、jpg等 ,可自行设置

@param image 图片

@param imageName 图片名字

@param extension 后缀,png,jpg

@param directoryPath 沙盒路径

@param EcmChatMyPic 沙盒路径下的文件夹

*/

+ (void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath{

    NSData *data  = UIImageJPEGRepresentation(image,.000000005);

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *createPath = [NSString stringWithFormat:@"%@/EcmChatMyPic", directoryPath];

    // 判断文件夹是否存在,如果不存在,则创建

    if (![[NSFileManager defaultManager]fileExistsAtPath:createPath]) {

        //如果没有就创建这个 想创建的文件夹  ()

        [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];

        //然后保存

        NSString * DocumentsPath = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents/EcmChatMyPic"];

        NSString *imgFileName = [NSString stringWithFormat:@"/%@.%@",imageName,extension];

        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:imgFileName]contents:data attributes:nil];

    } else {

        //文件夹存在  直接保存

        NSString * DocumentsPath = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents/EcmChatMyPic"];

        NSString *imgFileName = [NSString stringWithFormat:@"/%@.%@",imageName,extension];

        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:imgFileName]contents:data attributes:nil];

    }

}

在下来就是读取了

NSFileManager *fileManager = [NSFileManager defaultManager];   

NSString *document=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *folder =[document stringByAppendingPathComponent:@"EcmChatMyPic"];

NSArray *fileList ;

    fileList =[fileManager contentsOfDirectoryAtPath:folder error:NULL];

    for (NSString *file in fileList) {

        NSLog(@"file=%@",file);

        NSString *path =[folder stringByAppendingPathComponent:file];

        NSLog(@"得到的路径=%@",path);

    }

fileList储存的就是所有文件路径的唯一标识,使用的时候就直接使用 path

这样就实现类分类存储

上一篇 下一篇

猜你喜欢

热点阅读