我正在尝试使用smartAlbum生成仅视频或仅照片或两者的数组。
您可以在下面看到我的代码:
PHFetchResult *collectionList = [PHCollectionList fetchMomentListsWithSubtype:PHCollectionListSubtypeMomentListCluster options:nil];
PHFetchOptions *options = nil;
if (self.xSelected) {
options = [[PHFetchOptions alloc] init];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
options.predicate = [NSPredicate predicateWithFormat:@"mediaType = %d",PHAssetMediaTypeImage];
}
if (self.ySelected) {
options = [[PHFetchOptions alloc] init];
options.predicate = [NSPredicate predicateWithFormat:@"mediaType = %d",PHAssetMediaTypeVideo];
}
[collectionList enumerateObjectsUsingBlock:^(PHCollectionList *collection, NSUInteger idx, BOOL *stop) {
PHFetchResult *momentsInCollection = [PHAssetCollection fetchMomentsInMomentList:collection options:options];
for (id moment in momentsInCollection) {
PHAssetCollection *castedMoment = (PHAssetCollection *)moment;
[_smartAlbums insertObject:castedMoment atIndex:0];
}
}];
但是,这在
block
的第一行中不断中断,并给出以下错误:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported predicate in fetch options: mediaType == 2'
我做了一些研究,发现了这个link。
我想知道这是Apple bug还是我的代码有问题。
对于引用此answer的人来说,它似乎奏效了,这很奇怪,因为它基本上是同一回事。
提前致谢,
阿尼什
编辑:
我想我在Apple文档中找到了答案here。看起来mediaType仅是
PHAsset
的键,而不是PHAssetCollection
的键。所以现在我想问题是如何仅使用视频或仅图像来获取PFAssetCollection
。 最佳答案
使用此方法可以分别获取照片和视频 Assets 阵列。
获取所有视频
func getAllVideos(completion:@escaping (_ videoAssets : [PHAsset]?) -> Void) {
var videoAssets : [PHAsset] = []
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",ascending: false)]
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.video.rawValue)
let allVideo = PHAsset.fetchAssets(with: .video, options: fetchOptions)
allVideo.enumerateObjects { (asset, index, bool) in
videoAssets.append(asset)
}
completion(videoAssets)
}
获取所有照片
func getAllPhotos(completion:@escaping (_ photosAssets : [PHAsset]?) -> Void) {
var photosAssets : [PHAsset] = []
let fetchOptions = PHFetchOptions()
let scale = UIScreen.main.scale
let screenWidth = UIScreen.main.bounds.width * scale
let screenHeight = UIScreen.main.bounds.height * scale
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",ascending: false)]
fetchOptions.predicate = NSPredicate(format: "mediaType = %d || (mediaSubtype & %d) != 0 && (pixelHeight != %d AND pixelWidth != %d) OR (pixelHeight != %d AND pixelWidth != %d)", PHAssetMediaType.image.rawValue, PHAssetMediaSubtype.photoLive.rawValue ,screenHeight, screenWidth, screenWidth, screenHeight)
let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
allPhotos.enumerateObjects { (asset, index, bool) in
photosAssets.append(asset)
}
completion(photosAssets)
}
关于ios - 错误: 'Unsupported predicate in fetch options: mediaType == 2' ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35590640/