我正在使用新的PHFetchOptions‘sortDescriptors从相机卷中获取PHAssets。似乎只有两个键可以排序: creationDate和modificationDate,这两个键都与您在Photos.app中看到的不同。
我是不是遗漏了什么?我们怎样才能让这件事起作用?
发布于 2015-04-29 16:12:50
我使用了以下代码来获取包括“相机卷”在内的智能相册列表:
// get the smart albums
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
for (NSInteger i = 0; i < smartAlbums.count; i++) {
PHAssetCollection *assetCollection = smartAlbums[i];
// Then use the following to get the photo images:
PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
}默认的排序顺序是集合中资产的现有顺序,包括“相机卷”。为选项传递"nil“将获得缺省值。您可以重新排序相机卷中的图像,此代码将反映更改。
发布于 2016-07-14 03:17:33
有一个超级简单的解决方案。
这样,您将得到与Photo.app完全相同的流顺序。
希望你觉得这有帮助。:]
发布于 2019-06-15 14:16:46
按照@Majotron的回答,我想在photos应用程序中以All Photos相册的形式,以准确的顺序获取所有用户的照片,并且只提供图像资源。
下面是我如何设置我的PHFetchOptions
let allPhotosOption = PHFetchOptions()
// Fetch only image asset
allPhotosOption.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
// Get All Photos album collection
let userLibrary = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil).firstObject
allPhotosResult = PHAsset.fetchAssets(in: userLibrary!, options: allPhotosOption)并在TableView/CollectionView中使用反向索引获取特定资产:
let asset = allPhotosResult.object(at: allPhotosResult.count - indexPath.item - 1)另外,如果您正在收听照片库的更改,请小心,并相应地重新排列您的视图。当更改与删除相关时,使用fetch结果获取反向索引,否则使用.fetchResultAfterChanges。
以下是我的处理方法:
func photoLibraryDidChange(_ changeInstance: PHChange) {
...
DispatchQueue.main.sync {
let originalCount = fetchResult.count
fetchResult = changes.fetchResultAfterChanges
if changes.hasIncrementalChanges {
guard let collectionView = self.collectionView else { return }
collectionView.performBatchUpdates({
if let removed = changes.removedIndexes, removed.count > 0 {
collectionView.deleteItems(at: removed.map({ IndexPath(item: originalCount - $0 - 1, section: 0) }))
}
if let inserted = changes.insertedIndexes, inserted.count > 0 {
collectionView.insertItems(at: inserted.map({ IndexPath(item: fetchResult.count - $0 - 1, section: 0) }))
}
})
// Avoid deleting and reloading same index path at one update
collectionView.performBatchUpdates({
if let changed = changes.changedIndexes, changed.count > 0 {
collectionView.reloadItems(at: changed.map({ IndexPath(item: fetchResult.count - $0 - 1, section: 0) }))
}
changes.enumerateMoves { fromIndex, toIndex in
collectionView.moveItem(at: IndexPath(item: fetchResult.count - $0 - 1, section: 0),
to: IndexPath(item: fetchResult.count - $0 - 1, section: 0))
}
})
} else {
collectionView!.reloadData()
}
...
}
}https://stackoverflow.com/questions/29022637
复制相似问题