iOS 8照片框架:使用iOS8获取所有相册的列表
如何在iOS8中获取所有collections的列表,包括相机胶卷(现在称为时刻)?
在iOS 7中,我使用ALAssetGroup枚举块,但不包括iOS时刻,这似乎与iOS7中的“相机胶卷”相当。
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) { if (group == nil) {// We're done enumerating return; } [group setAssetsFilter:[ALAssetsFilter allAssets]]; if ([[sGroupPropertyName lowercaseString] isEqualToString:@"camera roll"] && nType == ALAssetsGroupSavedPhotos) { [_assetGroups insertObject:group atIndex:0]; } else { [_assetGroups addObject:group]; } }; // Group Enumerator Failure Block void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) { SMELog(@"Enumeration occured %@", [error description]); }; // Enumerate Albums [_library enumerateGroupsWithTypes:kSupportedALAlbumsMask usingBlock:assetGroupEnumerator failureBlock:assetGroupEnumberatorFailure]; }];
使用PhotosFramework有点不同,你可以达到相同的结果,但你只需要做到这一点。
1)获取所有的照片(在iOS8的瞬间,或相机胶卷之前)
PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
(可选)如果您希望按创builddatesorting,则只需添加PHFetchOptions
如下所示:
PHFetchOptions *allPhotosOptions = [PHFetchOptions new]; allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]]; PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:allPhotosOptions];
现在,如果你想要,你可以从PHFetchResult
对象获取资源:
[allPhotosResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) { NSLog(@"asset %@", asset); }];
2)获取所有的用户相册(例如附加sorting只显示至less有一张相片的相册)
PHFetchOptions *userAlbumsOptions = [PHFetchOptions new]; userAlbumsOptions.predicate = [NSPredicate predicateWithFormat:@"estimatedAssetCount > 0"]; PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:userAlbumsOptions]; [userAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) { NSLog(@"album title %@", collection.localizedTitle); }];
对于从PHFetchResult *userAlbums
返回的每个PHAssetCollection
,您可以像这样获取PHAssets
(甚至可以将结果限制为仅包含照片资源):
PHFetchOptions *onlyImagesOptions = [PHFetchOptions new]; onlyImagesOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeImage]; PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:onlyImagesOptions];
3)获取智能相册
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil]; [smartAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) { NSLog(@"album title %@", collection.localizedTitle); }];
智能相册需要注意的一点是,如果无法确定estimatedAssetCount,则collection.estimatedAssetCount
可以返回NSNotFound
。 如标题所示,这是估计的。 如果你想确定一些资产,你必须执行提取并得到这样的计数:
PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
资产数量= assetsFetchResult.count
苹果有一个样例项目,可以做你想做的事情:
library/content/samplecode/UsingPhotosFramework/ExampleappusingPhotosframework.zip (你必须是注册开发者才能访问这个)
这只是@拉迪斯拉夫对Swift高超的接受答案的翻译:
// *** 1 *** // Get all photos (Moments in iOS8, or Camera Roll before) // Optionally if you want them ordered as by creation date, you just add PHFetchOptions like so: let allPhotosOptions = PHFetchOptions() allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] let allPhotosResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: allPhotosOptions) // Now if you want you can get assets from the PHFetchResult object: allPhotosResult.enumerateObjectsUsingBlock({ print("Asset \($0.0)") }) // *** 2 *** // Get all user albums (with additional sort for example to only show albums with at least one photo) let userAlbumsOptions = PHFetchOptions() userAlbumsOptions.predicate = NSPredicate(format: "estimatedAssetCount > 0") let userAlbums = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.Any, options: userAlbumsOptions) userAlbums.enumerateObjectsUsingBlock( { if let collection = $0.0 as? PHAssetCollection { print("album title: \(collection.localizedTitle)") //For each PHAssetCollection that is returned from userAlbums: PHFetchResult you can fetch PHAssets like so (you can even limit results to include only photo assets): let onlyImagesOptions = PHFetchOptions() onlyImagesOptions.predicate = NSPredicate(format: "mediaType = %i", PHAssetMediaType.Image.rawValue) if let result = PHAsset.fetchKeyAssetsInAssetCollection(collection, options: onlyImagesOptions) { print("Images count: \(result.count)") } } } ) // *** 3 *** // Get smart albums let smartAlbums = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .AlbumRegular, options: nil) // Here you can specify Photostream, etc. as PHAssetCollectionSubtype.xxx smartAlbums.enumerateObjectsUsingBlock( { if let assetCollection = $0.0 as? PHAssetCollection { print("album title: \(assetCollection.localizedTitle)") // One thing to note with Smart Albums is that collection.estimatedAssetCount can return NSNotFound if estimatedAssetCount cannot be determined. As title suggest this is estimated. If you want to be sure of number of assets you have to perform fetch and get the count like: let assetsFetchResult = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil) let numberOfAssets = assetsFetchResult.count let estimatedCount = (assetCollection.estimatedAssetCount == NSNotFound) ? -1 : assetCollection.estimatedAssetCount print("Assets count: \(numberOfAssets), estimate: \(estimatedCount)") } } )
试试这个代码…
self.imageArray = [[NSArray alloc] init];
PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init]; requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact; requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat; requestOptions.synchronous = true; PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil]; NSLog(@"%d",(int)result.count); PHImageManager *manager = [PHImageManager defaultManager]; NSMutableArray *images = [NSMutableArray arrayWithCapacity:countValue]; // assets contains PHAsset objects. __block UIImage *ima; for (PHAsset *asset in result) { // Do something with the asset [manager requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:requestOptions resultHandler:^void(UIImage *image, NSDictionary *info) { ima = image; [images addObject:ima]; }]; self.imageArray = [images copy];