Search code examples
iosuiviewavplayerios11avkit

AVPlayer Inside A UIView


So I have a view on my HomeViewController that I want to play a video inside of. on viewDidLoad() I am calling playVideo() here is my code:

func playVideo() {
    guard let filePath = Bundle.main.path(forResource: "video", ofType: "mov") else {
        debugPrint("video.mov not found.")
        return
    }

    let avPlayer = AVPlayer(url: URL(fileURLWithPath: filePath))
    let avPlayerController = AVPlayerViewController()
    avPlayerController.player = avPlayer
    avPlayerController.view.frame = playerView.bounds
    avPlayerController.showsPlaybackControls = false
    avPlayerController.player?.play()
    playerView.addSubview(avPlayerController.view)
    playerView.bringSubview(toFront: QRButton)
}

All I get is a black background and no video. What am I doing wrong? I have tried to solve this for a while now.

iOS: 11.2 beta
Xcode: 9.2 beta


Solution

  • Try to use avPlayer as a class variable, maybe it has been released before it can start to play.

    class ViewController: UIViewController {
         var avPlayer:AVPlayer?
    
        func playVideo() {
        guard let filePath = Bundle.main.path(forResource: "video", ofType: "mov") else {
            debugPrint("video.mov not found.")
            return
        }
    
        avPlayer? = AVPlayer(url: URL(fileURLWithPath: filePath))
        let avPlayerController = AVPlayerViewController()
        avPlayerController.player = avPlayer
        avPlayerController.view.frame = playerView.bounds
        avPlayerController.showsPlaybackControls = false
        avPlayerController.player?.play()
        playerView.addSubview(avPlayerController.view)
        playerView.bringSubview(toFront: QRButton)
     }
    }