Swift-如何获取.Mov格式?

时间:2019-01-09 16:33:09

标签: ios swift nspredicate phasset

我发现了许多使用

获取视频或图像的解决方案
phfetchOptions.predicate = NSPredicate(format : "mediaType = %d" , PHAssetMediaType.video.rawvalue)

还有一个PHAssetMediaSubtype,它与我要寻找的完全不同。

如何确切地从PHAsset内的所有其他格式中获取.Mov文件的数量

我已经接近解决方案,但我想这不是获得计数的正确方法。创建后台调用数量的视频数量,而该过程应在一个异步调用中完成。有什么建议吗?

 private func getMovVideosCount() {

    let fetchOptions = PHFetchOptions()

    fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.video.rawValue)
    var count : Int = 0
    let imagesAndVideos = PHAsset.fetchAssets(with: fetchOptions)
    for i in 0..<imagesAndVideos.count {
        let videoRequestOptions = PHVideoRequestOptions()
        PHImageManager.default().requestPlayerItem(forVideo: imagesAndVideos[i], options: videoRequestOptions) { (playerItem, result) in
            let currentVideoUrlAsset = playerItem?.asset as?  AVURLAsset
            if let currentVideoFilePAth = currentVideoUrlAsset?.url{
                let lastObject = currentVideoFilePAth.pathExtension
                if lastObject == "MOV" {
                    count += 1
                }
            }
            print(Thread.isMainThread) // false 
        }
    }
    print(Thread.isMainThread) // true
}

1 个答案:

答案 0 :(得分:1)

此解决方案提供了.MOV的计数并解决了调度组的并发问题。

private func getMovVideosCount() {

let fetchOptions = PHFetchOptions()
let dispatchgroup = DispatchGroup()
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.video.rawValue)
var count : Int = 0
let imagesAndVideos = PHAsset.fetchAssets(with: fetchOptions)
for i in 0..<imagesAndVideos.count {
    dispatchgroup.start()
    let videoRequestOptions = PHVideoRequestOptions()
    PHImageManager.default().requestPlayerItem(forVideo: imagesAndVideos[i], options: videoRequestOptions) { (playerItem, result) in
        let currentVideoUrlAsset = playerItem?.asset as?  AVURLAsset
        if let currentVideoFilePAth = currentVideoUrlAsset?.url{
            let lastObject = currentVideoFilePAth.pathExtension
            if lastObject == "MOV" {
                count += 1
            }
        }
        print(Thread.isMainThread) // false 
      dispatchgroup.leave()
    }
}
dispatchgroup.notify({})
print(Thread.isMainThread) // true

}