1

I am building one simple game where I need to display 2 videos to user frequently videos are in my bundle locally. I just want to play that videos on my viewcontroller. My code for that is :

let playerItem = AVPlayerItem(URL: NSURL.fileURLWithPath("\(vdoPath)")) //vdoPath will be random of that two local video files from bundle
let player = AVPlayer(playerItem: playerItem)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
playerViewController.view.backgroundColor = UIColor.clearColor()
playerViewController.showsPlaybackControls = false
playerViewController.view.frame = self.playerView.bounds
self.playerView.addSubview(playerViewController.view)
self.addChildViewController(playerViewController)
player.play() 

AVPlayer plays videos for sometimes like I am not facing issue till 12-15 times but when I continue to play more AVPlayer not able to play it showing like this: There is no issue with my file and path because before getting this I am able to play 12-15 times as I said. please give me proper solution and reason behind this.

enter image description here

sohan vanani
  • 1,537
  • 1
  • 20
  • 37

2 Answers2

4

For people facing this issue in the future and @JAck's solution not working, here's a solution that worked for me. By the way, my screen was just black. It didn't have the play button with a slash through it... But anyways, the underlying issue for me was that I had too many instances of AVPlayer and AVPlayerLayer (Apple apparently caps this number). Though I was removing the layer and pausing the player when dismissing the view controller, the player was still being retained (I'm guessing). So, my fix was to nil out BOTH the player instance and the player layer instance. Here's my code:

var player: AVPlayer?
var layer: AVPlayerLayer?

Right before dismissing my view controller, I add this snippet:

 DispatchQueue.main.async {
        self.player?.pause()
        self.player = nil
        self.layer?.removeFromSuperlayer()
        self.layer = nil
}
joe
  • 267
  • 3
  • 8
  • Is there a way to find out player or layer instances that haven't been nilled and removed? – Baki Aug 04 '17 at 11:20
2

You need to use player.replacePlayerItem(item) instead of twice calling if still not working ask me anytime. First let AVPlayer play first video then wait your controller till completion then start another.

JAck
  • 854
  • 9
  • 18