iOS應(yīng)用保存圖片到應(yīng)用自定義的相冊(cè)

在很多應(yīng)用中,瀏覽圖片時(shí),可以長按圖片選擇保存到手機(jī)相冊(cè)中的自定義名稱相冊(cè)中,比如微博,它會(huì)在系統(tǒng)相冊(cè)中自動(dòng)創(chuàng)建一個(gè)名為“微博”的相冊(cè),并添加要保存的圖片到其中。在iOS8以后,我們可以使用 Photos 框架非常輕松的實(shí)現(xiàn)這個(gè)功能。

如需滿足 iOS8之前的版本,則可以使用 AssetsLibrary 框架,但是這個(gè)框架在 iOS9 后廢棄了。

一、Photos 框架簡(jiǎn)單介紹

1、重要的類

該框架有幾個(gè)非常重要的類:PHAsset、PHAssetCollection 和 PHLibrary。

PHAsset 表示一個(gè)圖片或者視頻文件
PHAssetCollection 表示圖片集合或者視頻集合,其實(shí)就是指相冊(cè)(包括了系統(tǒng)相冊(cè)和自定義相冊(cè))
PHLibrary 表示整個(gè)相冊(cè)庫,包括整個(gè)相冊(cè)和圖片等

2、查詢操作

查詢操作,直接使用 PHAsset 和 PHAssetCollection 類本身的方法

//1 獲取相冊(cè)中的圖片--傳入相冊(cè)圖片的 ID---返回一組圖片

[PHAsset fetchAssetsWithLocalIdentifiers:@[ID] options:nil];

//2 查詢手機(jī)中所有的相冊(cè)列表(分為系統(tǒng)相冊(cè)和自定義相冊(cè),通過控制傳入的參數(shù)來確定)---返回相冊(cè)組--類似數(shù)組-forin遍歷即可

[PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

3、增刪改操作

  1. 如果做查詢之外的操作,比如說保存圖片、創(chuàng)建自定義相冊(cè)、向自定義相冊(cè)中添加圖片等,都需要使用另外兩個(gè)類:PHAssetChangeRequestPHAssetCollectionChangeRequest

  2. 這些操作必須在 [[PHPhotoLibrary sharedPhotoLibrary]performChange...] 的 block 中間調(diào)用

//1 保存圖片

[PHAssetChangeRequest creationRequestForAssetFromImage:image];

//2 創(chuàng)建相冊(cè)

[PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@"自定義相冊(cè)"];

二、保存圖片到自定義相冊(cè)

1、判斷相冊(cè)訪問權(quán)限

保存圖片時(shí),首先我們要判斷應(yīng)用是否有對(duì)相冊(cè)的訪問權(quán)限,這個(gè)可以通過下面的代碼進(jìn)行簡(jiǎn)單的判斷:

- (BOOL)achiveAuthorizationStatus{
    
    // 1、判斷相冊(cè)訪問權(quán)限
    /*
     * PHAuthorizationStatusNotDetermined = 0, 用戶未對(duì)這個(gè)應(yīng)用程序的權(quán)限做出選擇
     * PHAuthorizationStatusRestricted, 此應(yīng)用程序沒有被授權(quán)訪問的照片數(shù)據(jù)??赡苁羌议L控制權(quán)限。
     * PHAuthorizationStatusDenied, 用戶已經(jīng)明確拒絕了此應(yīng)用程序訪問照片數(shù)據(jù).
     * PHAuthorizationStatusAuthorized, 用戶已授權(quán)此應(yīng)用訪問照片數(shù)據(jù).
     */
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
        // 沒權(quán)限
        UIAlertController *authorizationAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"沒有照片的訪問權(quán)限,請(qǐng)?jiān)谠O(shè)置中開啟" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:NULL];
        [authorizationAlert addAction:cancel];
        [self presentViewController:authorizationAlert animated:YES completion:nil];
        return NO;
    } else {
        return YES;
    }
}

2、將圖片保存到系統(tǒng)相冊(cè)

關(guān)于圖片或視頻保存到自定義相冊(cè),其實(shí)是先保存到系統(tǒng)相冊(cè),再將該圖片引用到我們創(chuàng)建的自定義相冊(cè),保存圖片或視頻一共有三種方式,代碼如下:

- (void)saveImageFromImage:(UIImage *)image{
    _saveType = 0;
    _targetImage = image;
    [self saveIntoAlbum];
}

- (void)saveImageFromFileURL:(NSURL *)url{
    
    _saveType = 1;
    _targetImageURL = url;
    [self saveIntoAlbum];
}

- (void)saveVideoFromFileURL:(NSURL *)url{
    _saveType = 2;
    _targetVideoURL = url;
    [self saveIntoAlbum];
}

- (void)saveIntoAlbum{
    
    // 1、判斷相冊(cè)訪問權(quán)限
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status != PHAuthorizationStatusAuthorized) {
            // 沒權(quán)限
            return ;
        }
        
        NSError *error = nil;
        // 2、有權(quán)限,保存相片到相機(jī)膠卷
        __block PHObjectPlaceholder *targetObject = nil;
        __weak typeof (self) weakself = self;

        switch (_saveType) {
            case 0:{
                [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
                    targetObject = [PHAssetCreationRequest creationRequestForAssetFromImage:_targetImage].placeholderForCreatedAsset;
                } error:&error];
                break;
            }
            case 1:{
                
                [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
                    targetObject = [PHAssetCreationRequest creationRequestForAssetFromImageAtFileURL:_targetImageURL].placeholderForCreatedAsset;
                } error:&error];
                break;
            }
            case 2:{
                [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
                    targetObject = [PHAssetCreationRequest creationRequestForAssetFromVideoAtFileURL:_targetVideoURL].placeholderForCreatedAsset;
                } error:&error];
                break;
            }
            default:
                break;
        }
        
        if (error) {
            NSLog(@"保存失?。?@", error);
            return;
        }
        // TODO: 將保存到系統(tǒng)的圖片或視頻引用保存到自定義相冊(cè)
    }];
}

3、創(chuàng)建/獲取自定義相冊(cè)

想要將圖片保存到自定義的相冊(cè),在進(jìn)行保存操作之前,需要獲取到我們創(chuàng)建的相冊(cè)對(duì)象,如果沒有獲取到,則創(chuàng)建,代碼如下:

// 獲取應(yīng)用名作為自定義相冊(cè)名
#define albumName [NSBundle mainBundle].infoDictionary[(NSString *)kCFBundleNameKey]
- (PHAssetCollection *)createdCollection {
    
    // 獲得所有的自定義相冊(cè)
    PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collection in collections) {
        if ([collection.localizedTitle isEqualToString:albumName]) {
            return collection;
        }
    }
    
    // 代碼執(zhí)行到這里,說明還沒有自定義相冊(cè)
    __block NSString *createdCollectionId = nil;
    
    // 創(chuàng)建一個(gè)新的相冊(cè)
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        createdCollectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumName].placeholderForCreatedAssetCollection.localIdentifier;
    } error:nil];
    
    if (createdCollectionId == nil) return nil;
    
    // 創(chuàng)建完畢后再取出相冊(cè)
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createdCollectionId] options:nil].firstObject;
}

4、保存到自定義相冊(cè)

如上所述,在以上步驟都完成后,則可以通過下面的代碼保存到自定義相冊(cè)了:

- (void)saveImageToCustomAlbum{
  
    // 3、拿到自定義的相冊(cè)對(duì)象
    PHAssetCollection *collection = [self createdCollection];
    if (collection == nil) return;
    
    // 4、保存
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        [[PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection] insertAssets:@[targetObject] atIndexes:[NSIndexSet indexSetWithIndex:0]];
    } error:&error];
    
    if (error) {
        NSLog(@"保存失?。?@", error);
    } else {
        NSLog(@"保存成功");
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容