iOS保存图片到新建相册(iOS Photos)

1.直接保存图片相册中(不需要自己创建新的相簿)

- (void)saveImage2Photo:(UIImage *)img {
    
    UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error == nil) {
        NSLog(@"保存成功");
    }

}

2.保存图片到自己创建相册中

有点复杂。。。这里不进行一些文字的概述,跟分析,直接上代码。

没经验的需要理解一些原理可参考以下两篇文章:


ObjC中国 Photos

Photos 框架实践以及坑(简书上一个兄弟的文章,挺不错)


四步骤进行:

1.授权判断

2.创建图片的请求(保存图片到相机胶卷中)

5.创建相簿请求

4.将刚刚添加到"相机胶卷"中的图片到"自己创建相簿"中请求


定一个全局的相册名字

//定义一个全局变量的相册名字
static NSString *photoAssetCollectionName = @"loukitphoto";

判断是否有权限访问相簿

//判断是否有权限访问相簿
-(void)phAuthorizationCheck{
    /*
     PHAuthorizationStatusNotDetermined,     用户还没有做出选择
     PHAuthorizationStatusDenied,            用户拒绝当前应用访问相册(用户当初点击了"不允许")
     PHAuthorizationStatusAuthorized         用户允许当前应用访问相册(用户当初点击了"好")
     PHAuthorizationStatusRestricted,        因为家长控制, 导致应用无法方法相册(跟用户的选择没有关系)
     */
    
    // 判断授权状态
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted) {
        NSLog(@"无法访问相簿--PHAuthorizationStatusRestricted");
    } else if (status == PHAuthorizationStatusDenied) {
        NSLog(@"无法访问相簿--PHAuthorizationStatusDenied");
    } else if (status == PHAuthorizationStatusAuthorized) {
        NSLog(@"可以访问相簿--PHAuthorizationStatusAuthorized");
        [self saveImage];
    } else if (status == PHAuthorizationStatusNotDetermined) {
        // 弹框请求用户授权
        NSLog(@"第一次访问--PHAuthorizationStatusNotDetermined");
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) { // 用户点击了好
                [self saveImage];
            }
        }];
    }
}
获取相簿(没有就创建,有就用)
//  获得相簿
-(PHAssetCollection *)createAssetCollection{
    
    //判断是否已存在
    PHFetchResult *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection * assetCollection in assetCollections) {
        if ([assetCollection.localizedTitle isEqualToString:photoAssetCollectionName]) {
            //说明已经有哪对象了
            return assetCollection;
        }
    }
    
    //创建新的相簿
    __block NSString *assetCollectionLocalIdentifier = nil;
    NSError *error = nil;
    //同步方法
    [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
        // 创建相簿的请求
        assetCollectionLocalIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:photoAssetCollectionName].placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    
    if (error)return nil;
    
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[assetCollectionLocalIdentifier] options:nil].lastObject;
}
保存图片
//保存图片
-(void)saveImage{
    
    __block  NSString *assetLocalIdentifier;
    [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
        
        //1.保存图片到相机胶卷中----创建图片的请求
        assetLocalIdentifier = [PHAssetCreationRequest creationRequestForAssetFromImage:self.imageView.image].placeholderForCreatedAsset.localIdentifier;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if(success == NO){
            NSLog(@"保存图片失败----(创建图片的请求)");
            return ;
        }
        
        // 2.获得相簿
        PHAssetCollection *createdAssetCollection = [self createAssetCollection];
        if (createdAssetCollection == nil) {
            NSLog(@"保存图片成功----(创建相簿失败!)");
            return;
        }
        
        // 3.将刚刚添加到"相机胶卷"中的图片到"自己创建相簿"中
        [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
            
            //获得图片
            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil].lastObject;
            //添加图片到相簿中的请求
            PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdAssetCollection];
            // 添加图片到相簿
            [request addAssets:@[asset]];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if(success){
                NSLog(@"保存图片到创建的相簿成功");
            }else{
                NSLog(@"保存图片到创建的相簿失败");
            }
        }];
    }];
}


你可能感兴趣的:(IOS笔记)