Search code examples
iosswiftnspredicatephasset

Swift - How to fetch a .Mov format?


I found many solution on fetching videos or image using

phfetchOptions.predicate = NSPredicate(format : "mediaType = %d" , PHAssetMediaType.video.rawvalue)

Also there is a PHAssetMediaSubtype which is very different what I am looking for.

How exactly to get the count of .Mov files from all other formats inside PHAsset

I got close to the solution but I guess this is not the proper way to get the count. Number of videos creating number of background calls instead the process should be done inside one async call. Any suggestions ?

 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
}

Solution

  • This solution gives the count of .MOV and solved the concurrency issues with dispatch group.

    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
    

    }