【发布时间】:2016-11-08 23:40:49
【问题描述】:
我正在使用“PHAsset”来获取相机胶卷资产。我正在使用
PHAsset.fetchAssetsWithMediaType(.Image, options: options)
用于获取所有画廊图像。但我想同时获取所有图像和视频并在集合视图中显示(如 Instagram 相机视图)。
谁能告诉我该怎么做?
【问题讨论】:
-
改进格式
我正在使用“PHAsset”来获取相机胶卷资产。我正在使用
PHAsset.fetchAssetsWithMediaType(.Image, options: options)
用于获取所有画廊图像。但我想同时获取所有图像和视频并在集合视图中显示(如 Instagram 相机视图)。
谁能告诉我该怎么做?
【问题讨论】:
这可能对你有用:
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 可能对您有用。只需准备好从结果集中过滤掉音频类型即可。
【讨论】:
免费使用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)
【讨论】:
实际解决方案(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) 确保您确实有授权并且可以访问照片库,否则会静默失败。
【讨论】: