将PHAsset获取结果限制为仅3个资产

时间:2021-06-25 21:51:38

I need to fetch three photos sorted by the date taken - latest being the most recently taken. The way I am currently doing this is by fetching all photo assets then fetching the asset at the appropriate indexes (0, 1, 2). While this works, I am curious if there is a more efficient way to do this when I'm only interested in the top three. The docs explain the fetch doesn't return all image data - only metadata, but I still don't need to obtain all of the metadata. Is there a PHFetchOption I could use to limit the fetch, or an NSPredicate, or is that not necessary to worry about?

我需要按拍摄日期排序拍摄三张照片 - 最新拍摄的照片。我目前这样做的方法是获取所有照片资产,然后在适当的索引(0,1,2)处获取资产。虽然这有效,但我很好奇是否有一种更有效的方法可以做到这一点,因为我只对前三名感兴趣。文档解释了fetch不会返回所有图像数据 - 只返回元数据,但我仍然不需要获取所有元数据。我可以使用PHFetchOption来限制获取或NSPredicate,还是不必担心?

var assetsFetchResults = PHAsset.fetchAssetsWithMediaType(.Image, options: nil)
let imageManager = PHCachingImageManager()

if assetsFetchResults?.count > 0 {
    var asset = assetsFetchResults?[0] as? PHAsset
    imageManager.requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: nil, resultHandler: ...)
}
//repeat for index 1 and 2 

1 个解决方案

#1


so with iOS 9 you can set PHFetchOptions setting to limit how many you fetch. For example:

因此,对于iOS 9,您可以设置PHFetchOptions设置以限制您获取的数量。例如:

   let fetchOptions = PHFetchOptions()
    if #available(iOS 9.0, *) {
        fetchOptions.fetchLimit = 3
    } else {
        // Fallback on earlier versions
    }

However I am also looking for a way to do this on iOS 8 devices as we still have to support both iOS 8 and 9 at this point

但是我也在寻找在iOS 8设备上执行此操作的方法,因为此时我们仍然需要支持iOS 8和9

#1


so with iOS 9 you can set PHFetchOptions setting to limit how many you fetch. For example:

因此,对于iOS 9,您可以设置PHFetchOptions设置以限制您获取的数量。例如:

   let fetchOptions = PHFetchOptions()
    if #available(iOS 9.0, *) {
        fetchOptions.fetchLimit = 3
    } else {
        // Fallback on earlier versions
    }

However I am also looking for a way to do this on iOS 8 devices as we still have to support both iOS 8 and 9 at this point

但是我也在寻找在iOS 8设备上执行此操作的方法,因为此时我们仍然需要支持iOS 8和9