将图片保存到沙盒或者相册

时间:2022-03-13 05:15:47

将图片保存到沙盒或者相册:
1.保存到相册:

-(void)saveImageToAlbum:(UIButton *)sender{
//将图片保存到相册中
UIImageWriteToSavedPhotosAlbum(self.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

2.保存到沙盒中

-(void)saveImageToSandBox:(UIButton *)sender{

//将图片保存到沙盒
//保存文件到沙盒
//获取沙盒中Documents目录路径
// NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

// NSLog(@"%@",documents);

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

NSLog(@"%@",documents);
//拼接文件绝对路径
NSString *path = [documents stringByAppendingPathComponent:self.fileName];

//保存
[self.results writeToFile:path atomically:YES];
}

//不管保存成功与失败都回调用该方法

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{

if (error != nil) {
UIAlertView *fail = [[UIAlertView alloc]initWithTitle:@"提示" message:@"保存失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[fail show];
NSLog(@"%@",error);
}
else{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"保存成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

[alert show];
[self.view addSubview:alert];
}
}