iOS 8照片框架:获取iOS8所有相册的列表

时间:2014-09-22 19:04:54

标签: ios8

如何在iOS8中获取所有集合的列表,包括相机胶卷(现在称为瞬间)?

在iOS 7中,我使用ALAssetGroup枚举块,但这并不包括iOS时刻,这似乎相当于iOS7中的Camera Roll。

    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];
    }];

3 个答案:

答案 0 :(得分:122)

使用Photos Framework有点不同,你可以达到相同的效果,你只需要部分完成。

1)获取所有照片(iOS8中的时刻或之前的相机胶卷)

PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];

如果您希望按创建日期排序,则可以选择添加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)获取所有用户相册(例如,仅显示包含至少一张照片的相册)

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);
}];

对于从PHAssetCollection返回的每个PHFetchResult *userAlbums,您可以像这样获取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);
}];

智能相册要注意的一件事是collection.estimatedAssetCount如果无法确定估计的AssetCount,则可以返回NSNotFound。标题表明这是估计的。如果您想确定必须执行的资产数量获取并获得如下计数:

PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];

资产数量= assetsFetchResult.count

Apple有一个样本项目可以满足您的需求:

https://developer.apple.com/library/content/samplecode/UsingPhotosFramework/ExampleappusingPhotosframework.zip(您必须是注册开发者才能访问此内容)

答案 1 :(得分:17)

这只是@ Ladislav对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)")
    }
} )

答案 2 :(得分:1)

试试此代码......

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];