首页 > 代码库 > 沙盒读写

沙盒读写

// "已经裁剪好的照片"写入到沙盒中

- (void)writeIntoSandboxWithImage:(UIImage *)image

{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSStringstringWithFormat:Sandbox_Avater]];   // 保存文件的名称

    BOOL result = [UIImagePNGRepresentation(image)writeToFile:path atomically:YES]; // 保存成功会返回YES

    if (result) {

        DEBUGLog(@"‘裁剪好的头像or初始头像写入到沙盒:成功");

    } else {

        DEBUGLog(@"‘裁剪好的头像or初始头像写入到沙盒:失败");

    }

}

 

// 从沙盒中读取"原来保存的照片"

- (UIImage *)readFromSandboxWithPath:(NSString *)path

{

    // 拿到应用程序沙盒里面的路径

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

    // 读取存在沙盒里面的文件图片

    NSString *imgPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:path];

    // 因为拿到的是个路径把它加载成一个data对象

    NSData *data = http://www.mamicode.com/[NSDatadataWithContentsOfFile:imgPath];

    // 直接把该图片读出来

    UIImage *image = [UIImageimageWithData:data];

    

    return image;

}

沙盒读写