从相机胶卷中获取图像和视频的Swift代码

11

我正在使用"PHAsset"来获取相机胶卷中的资源。我正在使用

PHAsset.fetchAssetsWithMediaType(.Image, options: options)

用于获取所有图库图像。但我想同时获取所有图像和视频,并在集合视图中显示(类似于Instagram相机视图)。

请问有谁能告诉我如何做到这一点?


改进格式化 - Kld
3个回答

16

实际解决方案(适用于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)请确保您实际上已经获得了授权并可以访问照片库,否则它将会在静默失败。


请使用 mediaType = %d 而不是 mediaType == %d,这行代码的含义是什么? - Rakesh Mandloi

5

可以随意使用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)

谢谢,我可以知道如果我点击UICollectionViewCell如何播放那个视频吗? - Neeraj Joshi

4
这可能对您有所帮助:
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可能适用于您。只需准备好从结果集中过滤出音频类型。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接