- (void)saveImageToAlbum:(UIImage *)image albumName:(NSString *)albumName
{
if (albumName != nil && ![albumName isEqualToString:@""]) {
[self createAlbumInPhoneAlbum:albumName];
}
[self saveToAlbumWithMetadata:nil imageData:UIImagePNGRepresentation(image) customAlbumName:albumName completionBlock:^
{
//这里可以创建添加成功的方法
[ErrorMessage showErrorMessage:@"下载成功" inView:[UIApplication sharedApplication].keyWindow];
}failureBlock:^(NSError *error)
{
//处理添加失败的方法显示alert让它回到主线程执行,不然那个框框死活不肯弹出来
dispatch_async(dispatch_get_main_queue(), ^{
//添加失败一般是由用户不允许应用访问相册造成的,这边可以取出这种情况加以判断一下
if([error.localizedDescription rangeOfString:@"User denied access"].location != NSNotFound ||[error.localizedDescription rangeOfString:@"用户拒绝访问"].location!=NSNotFound){
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:error.localizedDescription message:error.localizedFailureReason delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) otherButtonTitles: nil];
[alert show];
}
});
}];
}
- (void)saveToAlbumWithMetadata:(NSDictionary *)metadata
imageData:(NSData *)imageData
customAlbumName:(NSString *)customAlbumName
completionBlock:(void (^)(void))completionBlock
failureBlock:(void (^)(NSError *error))failureBlock
{
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
void (^AddAsset)(ALAssetsLibrary *, NSURL *) = ^(ALAssetsLibrary *assetsLibrary, NSURL *assetURL) {
[assetsLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:customAlbumName]) {
[group addAsset:asset];
if (completionBlock) {
completionBlock();
}
}
} failureBlock:^(NSError *error) {
if (failureBlock) {
failureBlock(error);
}
}];
} failureBlock:^(NSError *error) {
if (failureBlock) {
failureBlock(error);
}
}];
};
[assetsLibrary writeImageDataToSavedPhotosAlbum:imageData metadata:metadata completionBlock:^(NSURL *assetURL, NSError *error) {
if (customAlbumName) {
[assetsLibrary addAssetsGroupAlbumWithName:customAlbumName resultBlock:^(ALAssetsGroup *group) {
if (group) {
[assetsLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
[group addAsset:asset];
if (completionBlock) {
completionBlock();
}
} failureBlock:^(NSError *error) {
if (failureBlock) {
failureBlock(error);
}
}];
} else {
AddAsset(assetsLibrary, assetURL);
}
} failureBlock:^(NSError *error) {
AddAsset(assetsLibrary, assetURL);
}];
} else {
if (completionBlock) {
completionBlock();
}
}
}];
}