我试图用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。 我还是想知道,这是一个苹果的错误,如果它只是一些错我的代码。 这似乎是它的工作对于提到这个answer,这太奇怪了怎么把它基本上是同样的事情的人。
提前致谢, 阿尼什
编辑:
我想我发现苹果的文档答案here。貌似mediaType的是仅适用于PHAsset
而不是PHAssetCollection
的关键。所以现在我想的问题是如何获得PFAssetCollection
仅视频或仅适用于图像。
使用此方法可分别获得照片和视频资产阵列。
获取所有视频
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)
}