图片保存到指定沙盒目录

代码示例

1、图片UIImage转二进制数据NSData

UIImage *image = [UIImage imageNamed:@"android"];
NSData *data = UIImageJPEGRepresentation(image, 1.0);

2、获取沙盒目录document

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

3、自定义沙盒目录images(即:/document/images)

NSString *directory = [path stringByAppendingPathComponent:@"images"];

4、创建自定义目录

if (![[NSFileManager defaultManager] fileExistsAtPath:directory]) {
            BOOL isSuccess = [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil];
            NSLog(@"目录创建:%@", (isSuccess ? @"成功" : @"失败"));
}

5、设置文件保存路径image.png(即:/document/images/image.png)

NSString *filePath = [directory stringByAppendingPathComponent:@"image.png"];

// 或
NSString *filePath = [directory stringByAppendingFormat:@"/%@", @"image.png"];

6、保存文件

BOOL isSuccess = [data writeToFile:filePath atomically:YES];
NSLog(@"文件保存:%@", (isSuccess ? @"成功" : @"失败"));
        
// 或
BOOL isSuccess = [[NSFileManager defaultManager] createFileAtPath:filePath contents:data attributes:nil];
NSLog(@"文件保存:%@", (isSuccess ? @"成功" : @"失败"));

你可能感兴趣的:(iOS,数据持久化)