照片框架PhotoKit使用記錄

1、創(chuàng)建自定義相冊(cè)并命名
- (PHAssetCollection * )createCollection{
    // 創(chuàng)建一個(gè)新的相冊(cè),查看所有的自定義相冊(cè),先查看是否有自己要?jiǎng)?chuàng)建的自定義相冊(cè),如果沒有自己要?jiǎng)?chuàng)建的自定義相冊(cè)那么我們就進(jìn)行創(chuàng)建
    NSString * title = [NSBundle mainBundle].infoDictionary[(NSString *)kCFBundleNameKey];
    PHFetchResult<PHAssetCollection *> *collections =  [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    PHAssetCollection * createCollection = nil; // 最終要獲取的自己創(chuàng)建的相冊(cè)
    for (PHAssetCollection * collection in collections) {
        if ([collection.localizedTitle isEqualToString:title]) {    // 如果有自己要?jiǎng)?chuàng)建的相冊(cè)
            createCollection = collection;
            break;
        }
    }
    if (createCollection == nil) {  // 如果沒有自己要?jiǎng)?chuàng)建的相冊(cè)
        // 創(chuàng)建自己要?jiǎng)?chuàng)建的相冊(cè)
        NSError * error1 = nil;
        __block NSString * createCollectionID = nil;
        // 這個(gè)方法會(huì)在相冊(cè)創(chuàng)建完畢后才會(huì)返回(同步返回)
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
            NSString * title = [NSBundle mainBundle].infoDictionary[(NSString *)kCFBundleNameKey];
            createCollectionID = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;
        } error:&error1];
        
        if (error1) {
            NSLog(@"創(chuàng)建相冊(cè)失敗...");
        }
        // 創(chuàng)建相冊(cè)之后我們還要獲取此相冊(cè)  因?yàn)槲覀円M(jìn)存儲(chǔ)相片
        createCollection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createCollectionID] options:nil].firstObject;
    }
    
    return createCollection;
}
2、保存圖片至相冊(cè)
- (void)saveImage:(UIImage *)image toCollection:(PHAssetCollection *)collection {
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        // 保存圖片至相機(jī)膠卷 并拿到這個(gè)圖片資源的標(biāo)識(shí)
        PHAssetChangeRequest *createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        PHObjectPlaceholder *assetPlaceholder = createAssetRequest.placeholderForCreatedAsset;
        // 將“相機(jī)膠卷”中的圖片添加到指定相冊(cè)
        PHAssetCollectionChangeRequest *albumChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
        [albumChangeRequest addAssets:@[assetPlaceholder]];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (error) {
            NSLog(@"success = %d, error = %@", success, error);
        }
    }];
}
3、從指定相冊(cè)讀取照片資源
- (PHFetchResult *)getImagesFromCollection:(PHAssetCollection *)collection {
    // 獲取所有資源的集合,并按資源的創(chuàng)建時(shí)間逆序排序
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    // 根據(jù)照片創(chuàng)建時(shí)間來倒序排列
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
    PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:options];
    return result;
}
4、刪除指定相冊(cè)的指定圖片
- (void)removeAsset:(PHAsset *)asset fromCollection:(PHAssetCollection *)collection {
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        // 將指定相冊(cè)的指定圖片移除(這里只是把照片從相冊(cè)中移除,照片依然存儲(chǔ)在手機(jī)的相冊(cè)膠卷中)
        PHAssetCollectionChangeRequest *albumChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
        [albumChangeRequest removeAssets:@[asset]];
        // 將“相機(jī)膠卷”中的指定圖片刪除掉
        [PHAssetChangeRequest deleteAssets:@[asset]];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (error) {
            NSLog(@"success = %d, error = %@", success, error);
        }
    }];
}
5、將相冊(cè)中的照片資源轉(zhuǎn)化為可用的image
PHFetchResult *result = [self getImagesFromCollection:_selfCollection];
    [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
        option.resizeMode = PHImageRequestOptionsResizeModeNone;
        // 照片是否同步處理圖像請(qǐng)求,設(shè)置為NO可能會(huì)多次調(diào)用resultHandle,設(shè)置為YES會(huì)阻塞調(diào)用線程直到圖像數(shù)據(jù)準(zhǔn)備好了或出現(xiàn)錯(cuò)誤
        option.synchronous = NO;
        // targetSize設(shè)置為PHImageManagerMaximumSize,則image會(huì)返回原始尺寸
        [[PHImageManager defaultManager] requestImageForAsset:(PHAsset *)obj targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:option resultHandler:^(UIImage * _Nullable imgResult, NSDictionary * _Nullable info) {
            // 是否原圖
            BOOL isOriginImg = ![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey] && ![[info objectForKey:PHImageResultIsDegradedKey] boolValue];

            if (isOriginImg) {
                // do something you want to do with UIImage
            }
        }];
    }];
最后編輯于
?著作權(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ù)。

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