Preview:
call video play code on action , not on viewdidload

import AVFoundation
import AVKit

 var playerController = AVPlayerViewController()
 var player: AVPlayer?
 var playerItem: AVPlayerItem?
 var playerObserver: Any?

class VideoPlayerViewController: UIViewController, AVPlayerViewControllerDelegate {

    var playerController = AVPlayerViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()

    }
  
  func playVideo(url: URL) {
        player = AVPlayer(url: url)
        playerItem = player?.currentItem

        // Observe the player's current time to detect playback start
        playerObserver = player?.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.001, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: .main) { [weak self] time in
            guard let self = self else { return }

            if let currentItem = self.playerItem {
                let currentTime = currentItem.currentTime().seconds
                 
                if currentTime > 0.001 { // Adjust the threshold as needed
                    SVProgressHUD.dismiss()

                    // Pause the player and remove the observer
                   // self.player?.pause()
                    self.player?.removeTimeObserver(self.playerObserver!)

                    // Present AVPlayerViewController now that playback has started
                    self.present(self.playerController, animated: true) {
                        self.playerController.player = self.player
                        self.playerController.player?.play()
                    }
                }
            }
        }

        SVProgressHUD.show()
        player?.play()
    }
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter