【问题标题】:Fetch only photos of type PHAssetMediaTypeImage form asset collection type PHAssetCollectionTypeSmartAlbum仅从资产集合类型 PHAssetCollectionTypeSmartAlbum 中获取 PHAssetMediaTypeImage 类型的照片
【发布时间】:2015-03-21 06:43:56
【问题描述】:

我正在使用 Photos 框架来获取 iOS8 中的相册列表。我可以使用

PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

这给了我所有智能相册的列表,包括视频。如何从此列表中过滤掉视频。我只需要图像。

我们将不胜感激。谢谢。

【问题讨论】:

    标签: ios photolibrary photokit phasset


    【解决方案1】:

    你应该设置抓取选项,它有一个属性predicate,可以用来过滤视频。下面是一个这样做的例子。

    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    //set up fetch options, mediaType is image.
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
    options.predicate = [NSPredicate predicateWithFormat:@"mediaType = %d",PHAssetMediaTypeImage];
    
    for (NSInteger i =0; i < smartAlbums.count; i++) {
        PHAssetCollection *assetCollection = smartAlbums[i];
        PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:options];
    
        NSLog(@"sub album title is %@, count is %ld", assetCollection.localizedTitle, assetsFetchResult.count);
        if (assetsFetchResult.count > 0) {
            for (PHAsset *asset in assetsFetchResult) {
                //you have got your image type asset.
            }
        }
    }
    

    【讨论】:

    • @grabler 它抛出了这个错误:Unsupported predicate in fetch options: mediaType == 1
    • @AnishKumar,不会发生在我身上,来自here,iOS 9.1 上的类似问题,尝试升级到 iOS 9.2。
    • @AnishKumar @gabbler 来自开发者论坛的链接线程是关于一个涉及title 而不是mediaType 的谓词。尝试在 PHAssetCollection.fetchAssetCollectionsWithType() 上使用此谓词时遇到此错误。从Developer documentation可以看出mediaType不支持获取PHAssetCollections只获取PHAsset
    【解决方案2】:

    在 swift 中做同样的事情:

    let fetchOptions = PHFetchOptions()
    fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue)
    

    【讨论】:

      猜你喜欢
      • 2019-12-04
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 2022-12-18
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多