'AVPlayer layer not showing video content sometimes

AVPlayer layer not showing video content sometimes but plays audio. This happens some times not each time Here is my lines of code :

 override func viewDidLoad() {
        super.viewDidLoad()
        self.tempVideoPath = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("tmpMov.mov")
        self.player = AVPlayer(url: self.tempVideoPath!)
}

 override func viewDidAppear(_ animated: Bool) {
     super.viewDidAppear(animated)
     self.playerLayer = AVPlayerLayer(player: self.player)
     self.playerLayer?.frame = self.videoPlayer.bounds
     self.playerLayer?.backgroundColor = UIColor.yellow.cgColor
     self.videoPlayer.layer.addSublayer(playerLayer!)
     print("player = \(playerLayer?.bounds)")

 }

Help me to solve this issue.



Solution 1:[1]

the problem with you code is that the bounds of videoPlayer can change. So you need to add the following code to your view controller to change AVPlayerLayer's frame accordingly:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    playerLayer?.frame = view.bounds
}

Hope it helps.

Solution 2:[2]

Although the videoplayer has been initialized correctly or created from storyboard, it seems that the layer is non-existent and creates this annoying problem.

At the beginning of your viewDidAppear first, try to create the layer , than add to it>

let layer = CALayer()
self.videoPlayer.layer = layer
//self.playerView.wantsLayer = true // this line is only for osx

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jajo
Solution 2 Alessandro Ornano