本文實現Photos.framework的常見功能,包括:創建自定義相冊、保存圖片到自定義相冊、搜索所有相冊的圖片,具體內容如下
1、保存圖片到相冊
/** * 保存圖片到相冊 */ - (IBAction)saveImage { PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus]; if (status == PHAuthorizationStatusDenied) { NSLog(@"請到【設置-隱私-照片】打開訪問開關"); } else if (status == PHAuthorizationStatusRestricted) { NSLog(@"無法訪問相冊"); } else { // 保存相片的標識 __block NSString *assetId = nil; [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ // 保存相片到相機膠卷,並返回標識 assetId = [PHAssetCreationRequest creationRequestForAssetFromImage:[UIImage imageNamed:@"logo"]].placeholderForCreatedAsset.localIdentifier; } completionHandler:^(BOOL success, NSError * _Nullable error) { if (!success) { NSLog(@"保存失敗:%@", error); return; } // 根據標識獲得相片對象 PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil].lastObject; // 拿到自定義的相冊對象 PHAssetCollection *collection = [self collection]; if (collection == nil) return; // 保存相片到自定義相冊中 [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ [[PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection] addAssets:@[asset]]; } completionHandler:^(BOOL success, NSError * _Nullable error) { if (success) { NSLog(@"保存成功"); } else { NSLog(@"保存失敗:%@", error); } }]; }]; } }
2、搜索所有相片
/** * 查詢所有的圖片 */ - (IBAction)searchAllImages { // 遍歷所有的自定義相冊 PHFetchResult<PHAssetCollection *> *collectionResult0 = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil]; for (PHAssetCollection *collection in collectionResult0) { [self searchAllImagesInCollection:collection]; } // 獲得相機膠卷的圖片 PHFetchResult<PHAssetCollection *> *collectionResult1 = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil]; for (PHAssetCollection *collection in collectionResult1) { if (![collection.localizedTitle isEqualToString:@"Camera Roll"]) continue; [self searchAllImagesInCollection:collection]; break; } } /** * 查詢某個相冊裡面的所有圖片 */ - (void)searchAllImagesInCollection:(PHAssetCollection *)collection { // 采取同步獲取圖片(只獲得一次圖片) PHImageRequestOptions *imageOptions = [[PHImageRequestOptions alloc] init]; imageOptions.synchronous = YES; NSLog(@"相冊名字:%@", collection.localizedTitle); // 遍歷這個相冊中的所有圖片 PHFetchResult<PHAsset *> *assetResult = [PHAsset fetchAssetsInAssetCollection:collection options:nil]; for (PHAsset *asset in assetResult) { // 過濾非圖片 if (asset.mediaType != PHAssetMediaTypeImage) continue; // 圖片原尺寸 CGSize targetSize = CGSizeMake(asset.pixelWidth, asset.pixelHeight); // 請求圖片 [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:targetSize contentMode:PHImageContentModeDefault options:imageOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) { NSLog(@"圖片:%@", result); }]; } }
以上就是本文的全部內容,希望對大家的學習有所幫助。