iOS 保存图片到自定义相册

项目中为了方便查看保存的图片,需要把图片保存到自定义的相册中,具体代码如下:

1、先检查相册权限

- (void)saveImageToAlbumWithName:(NSString *)albumName image:(UIImage *)image {
    //判断授权状态
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusAuthorized) { //已授权
        [self saveImageWithImage:image albumName:albumName];
    } else if (status == PHAuthorizationStatusDenied) { //拒绝
        NSLog(@"请打开访问相册的权限");
    } else if (status == PHAuthorizationStatusNotDetermined) { //未决定
        // 弹框请求用户授权
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) { // 用户点击了好
                [self saveImageWithImage:image albumName:albumName];
            }
        }];
    } else if (status == PHAuthorizationStatusRestricted) { //家长控制模式限制
        NSLog(@"因为系统原因, 无法访问相册");
    }
}

2、创建自定义相册

- (PHAssetCollection *)creatPHAssetWithAlbumName:(NSString *)albumName {
    
    //从已经存在的相簿中查找应用对应的相册
    PHFetchResult *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collection in assetCollections) {
        if ([collection.localizedTitle isEqualToString:albumName]) {
            return collection;
        }
    }
    // 没找到,就创建新的相簿
    NSError *error;
    __block NSString *assetCollectionLocalIdentifier = nil;
    //这里用wait请求,保证创建成功相册后才保存进去
    [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{

        assetCollectionLocalIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumName].placeholderForCreatedAssetCollection.localIdentifier;
        
    } error:&error];
    
    if (error) return nil;
    
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[assetCollectionLocalIdentifier] options:nil].lastObject;
}

3、保存图片

- (void)saveImageWithImage:(UIImage *)image albumName:(NSString *)albumName {
    // PHAsset : 一个资源,一个图片
    // PHAssetCollection : 一个相簿 (也可以说是一个相册)
    // PHotoLibrary 整个照片库(里面会有很多相册)
    
    __block NSString *assetLocalIdentifier = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        
        // 1.保存图片到相机胶卷中
        assetLocalIdentifier = [PHAssetChangeRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        
        if (success == NO || error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"保存照片失败");
            });
            return;
        }
        
        // 2. 获得相册
        PHAssetCollection *creatAssetCollction = [self creatPHAssetWithAlbumName:albumName];
        if (creatAssetCollction == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"创建相册失败");
            });
            return;
        }
        
        //创建成功,就把图片保存到相册中
        [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
            
            //添加相机胶卷中的图片到相簿中去
            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil].lastObject;
            //添加图片到相册中的请求
            PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:creatAssetCollction];
            [request addAssets:@[asset]];
            
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            
            if (success == NO || error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                  NSLog("保存图片失败");
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                  NSLog(@"保存图片成功");
                });
            }
        }];
        
    }];
}

你可能感兴趣的:(iOS 保存图片到自定义相册)