我正在使用"PHAsset"来获取相机胶卷中的资源。我正在使用
PHAsset.fetchAssetsWithMediaType(.Image, options: options)
用于获取所有图库图像。但我想同时获取所有图像和视频,并在集合视图中显示(类似于Instagram相机视图)。
请问有谁能告诉我如何做到这一点?
实际解决方案(适用于Swift 4和可能的Swift 3):在您的viewDidLoad或适合您情况的任何位置调用checkAuthorizationForPhotoLibraryAndGet()。
private func getPhotosAndVideos(){
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",ascending: false)]
fetchOptions.predicate = NSPredicate(format: "mediaType = %d || mediaType = %d", PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue)
let imagesAndVideos = PHAsset.fetchAssets(with: fetchOptions)
print(imagesAndVideos.count)
}
private func checkAuthorizationForPhotoLibraryAndGet(){
let status = PHPhotoLibrary.authorizationStatus()
if (status == PHAuthorizationStatus.authorized) {
// Access has been granted.
getPhotosAndVideos()
}else {
PHPhotoLibrary.requestAuthorization({ (newStatus) in
if (newStatus == PHAuthorizationStatus.authorized) {
self.getPhotosAndVideos()
}else {
}
})
}
}
1)请确保使用mediaType = %d而不是mediaType == %d
2)请确保您实际上已经获得了授权并可以访问照片库,否则它将会在静默失败。
可以随意使用NSPredicate
。
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",
ascending: false)]
fetchOptions.predicate = NSPredicate(format: "mediaType == %d || mediaType == %d",
PHAssetMediaType.image.rawValue,
PHAssetMediaType.video.rawValue)
fetchOptions.fetchLimit = 100
let imagesAndVideos = PHAsset.fetchAssets(with: fetchOptions)
let allMedia = PHAsset.fetchAssetsWithOptions(fetchOptions)
let allPhotos = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions)
let allVideo = PHAsset.fetchAssetsWithMediaType(.Video, options: fetchOptions)
print("Found \(allMedia.count) media")
print("Found \(allPhotos.count) images")
print("Found \(allVideo.count) videos")
public enum PHAssetMediaType : Int {
case Unknown
case Image
case Video
case Audio
}
由于它不是一个OptionSetType
,所以您无法像位域一样将其组合用于PHAsset.fetchAssetsWithMediaType
,但PHAsset.fetchAssetsWithOptions
可能适用于您。只需准备好从结果集中过滤出音频类型。