Search code examples
iosswiftvideoavplayerphasset

app plays same video for all video PHAsset in swift


I have simple app which displays all videos from the photolibrary of iPhone (using PHAsset). I'm able to display thumbnail of all videos (in collection view) but when I tap any video it plays same video only, I did not hardcode any url. Below is the code, not sure where I'm wrong.

  1. getting the video assets
var va: PHFetchResult<PHAsset>!

override func viewDidLoad() {
    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false) ]
    fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.video.rawValue)
    va = PHAsset.fetchAssets(with: fetchOptions)
}
  1. When tapping the video thumbnail in the collection view, creating new UIViewController and passing the asset data
 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print(indexPath)
    let vc=videoVC()
    vc.vasset = self.va
    vc.passedContentOffset = indexPath
    self.navigationController?.pushViewController(vc, animated: true)
}
  1. Finally playing the video
let Newasset = allAssets1[indexPath.row]
PHCachingImageManager().requestAVAsset(forVideo: Newasset, options: nil) { (Newasset, audioMix, args) in
    let asset1 = asset as! AVURLAsset

    DispatchQueue.main.async {
        let player = AVPlayer(url: asset1.url)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        self.present(playerViewController, animated: true) {
            playerViewController.player!.play()
        }
    }
}

Really not sure where code is going wrong from my end.


Solution

  • you probably need to check the indexPath that you are passing and this should work.

    Change

    let Newasset = allAssets1[indexPath.row]
    

    to

    let Newasset = allAssets1[indexPath.item]