本文完成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); }]; } }
以上就是本文的全體內容,願望對年夜家的進修有所贊助。
【iOS完成圖片保留與搜刮功效】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!