iOS保存到相冊/創(chuàng)建自定義相簿

保存到相冊ios方法有很多 但是隨著技術的更新而且現(xiàn)在已經是iOS11了所以我只介紹最新的方法(其中授權代碼是iOS8出來的 保存相冊的/創(chuàng)建自定義的代碼是ios9出來的)

對于相冊我們應該分清楚幾個事情:

PHAsset :單個圖片

PHAssetCollection :一個相簿

保存到自定義相冊的步驟

  • 判斷授權狀態(tài)

  • 將圖片保存到相簿

  • 創(chuàng)建自定義的相薄

  • 將相片保存到自定義的相薄

我們開始的代碼書寫并且我將會介紹每一段代碼的意思

  • 開始請求授權
// 請求授權
[PHPhotoLibraryrequestAuthorization:^(PHAuthorizationStatusstatus) {
// 先判斷是否可以授權
switch(status) {
casePHAuthorizationStatusNotDetermined:
{
  XMGLOG(@"用戶還沒有開始做出選擇");
}
break;
  casePHAuthorizationStatusAuthorized:
{
XMGLOG(@"用戶授權了");
// 我們所有的操作都在這個方法里
  [selfsaveImage];
}
break;
default:
{
// 這里的狀態(tài)不在描述,文檔里有4種狀態(tài),寫的很明白
  XMGLOG(@"用戶不允許");
}
break;
}
}];
  • 在這里開始進行保存圖片和創(chuàng)建相簿的操作
    1)將圖片保存到系統(tǒng)的相簿(如果你只保存到系統(tǒng)的相簿不創(chuàng)建自定義的相簿后面的步驟可以不用看了)
/**
 *
 *   保存圖片到自定義的相冊
 */
- (void)saveImage {
// 根據(jù)蘋果的官方文檔,所有的改變/創(chuàng)建/刪除等的操作都要[PHPhotoLibrary sharedPhotoLibrary] performChanges:執(zhí)行或者 -[PHPhotoLibrary performChangesAndWait:] block里進行操作
 [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        // 1.將圖片保存到相簿
         [PHAssetCreationRequest creationRequestForAssetFromImage:self.downloadImage];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
}];
}

2)創(chuàng)建自定義的相簿(都是在saveimage方法里 后面不在復述)

// 其中collectionTitle 是相簿的名字 我寫的是全局的變量 在我的項目中我寫的是
static NSString *collectionTitle = @"百思不得姐的相簿";這個方法單單是創(chuàng)建相簿 注意:需要在第一步操作成功之后才能執(zhí)行這段代碼
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                 [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:collectionTitle];
                }
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
}];

2.1)第一步和第二部合起來的操作是

 [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        // 1.將圖片保存到相簿
  [PHAssetCreationRequest creationRequestForAssetFromImage:self.downloadImage];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            // 2.創(chuàng)建自定義的相薄
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
               [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:collectionTitle];
                }
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                if (success) {
                  
                }
            }];
        }
    }];

3)將圖片保存到我們創(chuàng)建的自定義的相簿(說明:按照我們的理解 collection可以添加asset但是看了頭文件他偏偏沒有,當時我真的郁悶了后來繼續(xù)查頭文件看到一個PHAssetCollectionChangeRequest有一個添加/刪除/插入等等的方法 所以我的思路就是:創(chuàng)建PHAssetCollectionChangeRequest(通過collection)然后添加asset,實際上并沒有我們想的這么簡單 我會在下面說的很清楚 )

 [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                        // 3. 將相片保存到自定義的相薄
                        PHAssetCollection *collection = nil;
                        PHAsset *asset = nil;
// 我剛才說了PHAssetCollectionChangeRequest 可以添加asset PHAssetCollectionChangeRequest的創(chuàng)建需要collection
                        PHAssetCollectionChangeRequest *requestCollection = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
                        // 添加進自定義的相冊
                        [requestCollection addAssets:@[asset]];
                    } completionHandler:^(BOOL success, NSError * _Nullable error) {
                        if (success) {
                            XMGLOG(@"保存相冊成功了 哈哈哈");
                        }
                    }];

3.1)我們現(xiàn)在的問題是怎樣拿到我們創(chuàng)建的相簿(collection)和對應圖片的asset

// 我們用這個方法拿到我們創(chuàng)建的自定義的相簿
collection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionIdentifier] options:nil].lastObject;

3.2)我們現(xiàn)在的問題又來了:怎樣拿到collectionIdentifier 下面的代碼是怎么樣拿到collectionIdentifier

// 其實我寫的第二步的時候我只寫了創(chuàng)建的代碼 實際上他也可以獲得localIdentifier,因此我們推倒出asset 也可以用同樣的思路獲得
collectionIdentifier =  [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:collectionTitle].placeholderForCreatedAssetCollection.localIdentifier;

3.3)下面是第三部完成的代碼

[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                        // 3. 將相片保存到自定義的相薄
                          PHAssetCollection *collection  = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionIdentifier] options:nil].lastObject;
                        PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetIdentifier] options:nil].lastObject;
                        PHAssetCollectionChangeRequest *requestCollection = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
                        // 添加進自定義的相冊
                        [requestCollection addAssets:@[asset]];
                    } completionHandler:^(BOOL success, NSError * _Nullable error) {
                        if (success) {
                            XMGLOG(@"保存相冊成功了 哈哈哈");
                        }
                    }];

3.4)1、2、3步合起來的為

    __block NSString *assetIdentifier = nil;
    __block NSString *collectionIdentifier = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        // 1.將圖片保存到相簿
        assetIdentifier = [PHAssetCreationRequest creationRequestForAssetFromImage:self.downloadImage].placeholderForCreatedAsset.localIdentifier;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            // 2.創(chuàng)建自定義的相薄
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
              collectionIdentifier =  [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:collectionTitle].placeholderForCreatedAssetCollection.localIdentifier;
                
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                if (success) {
                    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                        // 3. 將相片保存到自定義的相薄
                        PHAssetCollection *collection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionIdentifier] options:nil].lastObject;
                        PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetIdentifier] options:nil].lastObject;
                        PHAssetCollectionChangeRequest *requestCollection = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
                        // 添加進自定義的相冊
                        [requestCollection addAssets:@[asset]];
                    } completionHandler:^(BOOL success, NSError * _Nullable error) {
                        if (success) {
                            XMGLOG(@"保存相冊成功了 哈哈哈");
                        }
                    }];
                }
            }];
        }
    }];

3.4) 到這里 我和大家一樣 以為我們大功告成了 但是我運行app確實發(fā)現(xiàn)是可以保存到自定義的相簿了 系統(tǒng)的相簿也可以保存了 但是當我保存第二張圖片的時候發(fā)現(xiàn)創(chuàng)建兩個自定義相簿(而且每一個相簿只保存一張圖片,開始的想法是保存我們的collectiontitle到沙盒,但是我們卸了app在重新裝上還是有這個問題的)下面的代碼我修改了這個bug

__block PHAssetCollection *collection = nil;
// 獲取所有的自定義的相簿
   PHFetchResult<PHAssetCollection *> *results =  [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
   for (PHAssetCollection *getCollection in results) {
// 如果有我們要的名字說明存在我們之前創(chuàng)建過的相簿
       if ([getCollection.localizedTitle isEqualToString:collectionTitle]) 
           collection = getCollection;
       }
   }

3.5 所以我們需要對第二步和第三步進行修改

// 第二步修改為
if (!collection) {
                  collectionIdentifier =  [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:collectionTitle].placeholderForCreatedAssetCollection.localIdentifier;
                }
// 第三步修改為
// 3. 將相片保存到自定義的相薄
                        if (!collection) {
                           collection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionIdentifier] options:nil].lastObject;
                        }
                        PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetIdentifier] options:nil].lastObject;
                        PHAssetCollectionChangeRequest *requestCollection = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
                        // 添加進自定義的相冊
                        [requestCollection addAssets:@[asset]];

3.6)最后我們的綜合的代碼

__block PHAssetCollection *collection = nil;
    PHFetchResult<PHAssetCollection *> *results =  [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *getCollection in results) {
        if ([getCollection.localizedTitle isEqualToString:collectionTitle]) {
            collection = getCollection;
        }
    }
    __block NSString *assetIdentifier = nil;
    __block NSString *collectionIdentifier = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        // 1.將圖片保存到相簿
        assetIdentifier = [PHAssetCreationRequest creationRequestForAssetFromImage:self.downloadImage].placeholderForCreatedAsset.localIdentifier;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            // 2.創(chuàng)建自定義的相薄
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                if (!collection) {
                  collectionIdentifier =  [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:collectionTitle].placeholderForCreatedAssetCollection.localIdentifier;
                }
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                if (success) {
                    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                        // 3. 將相片保存到自定義的相薄
                        if (!collection) {
                           collection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionIdentifier] options:nil].lastObject;
                        }
                        PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetIdentifier] options:nil].lastObject;
                        PHAssetCollectionChangeRequest *requestCollection = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
                        // 添加進自定義的相冊
                        [requestCollection addAssets:@[asset]];
                    } completionHandler:^(BOOL success, NSError * _Nullable error) {
                        if (success) {
                            XMGLOG(@"保存相冊成功了 哈哈哈");
                        }
                    }];
                }
            }];
        }
    }];

3.7)說明:現(xiàn)在可以說我們終于寫完了 ,但是我還發(fā)現(xiàn)了一個小的小問題就是手機系統(tǒng)點擊“+”創(chuàng)建相簿還可以創(chuàng)建和我們一樣名字的相簿 我想了想 :這個是系統(tǒng)的問題我們管不著(我個人覺得蘋果這點不好)我們的現(xiàn)在的代碼block嵌套block 看起來不好 大家可以自己整理一下
3.8)如果還有不明白的 請看我的demo(搜索這個類XMGPhotoWatchViewController)
[鏈接]https://github.com/liudiange/practice1.git

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容