Search code examples
iosavplayeriphone-6swrevealviewcontroller

AVPlayer Crashes on Device When Dismissing View


I'm having an issue with the AVPlayer. I've tried many solutions but it still crashes after I move to a different view.

class GuideVideo : BaseViewController{

var avPlayer: AVPlayer?
var avPlayerLayer: AVPlayerLayer?

override func viewDidLoad() {
    super.viewDidLoad()
    generateVideo()
}

func generateVideo () {
    let videoURLWithPath = data["VideoUrl"]
    let videoFilePath = NSURL(string: videoURLWithPath!)

    let avAsset: AVAsset = AVAsset.assetWithURL(videoFilePath) as! AVAsset
    let avPlayerItem = AVPlayerItem(asset: avAsset)
    avPlayer = AVPlayer(playerItem: avPlayerItem)
    avPlayerLayer = AVPlayerLayer(player: avPlayer)

    avPlayerLayer!.frame = self.videoView.bounds
    self.videoView.layer.addSublayer(avPlayerLayer)
    avPlayer!.play()
}

I've also tried removing the observers from it since I assume the crash is related to a nil observer.

override func viewWillDisappear(animated: Bool) {
    dispatch_async(dispatch_get_main_queue(),{
        if self.avPlayerLayer != nil {
            self.avPlayerLayer!.player.pause()
            NSNotificationCenter.defaultCenter().removeObserver(self.avPlayerLayer!)
            self.avPlayerLayer!.removeFromSuperlayer()
            self.avPlayerLayer = nil
        }
        self.avPlayer!.pause()
        self.avPlayer = AVPlayer()
    })
    super.viewWillDisappear(animated)
}

Nothing works and the crash provides no data. Either it crashes without indicating a line or a general

Thread 1: EXC_BAD_ACCESS * Import thing to note is that this crash only happens on the iPhone 6/6+. Our iPhone 5C handles the class well. * I only get the crash after moving to another view controller or a different navigation stack, but a few seconds after the view had been dismissed.

Thank you, been sitting on this for the better part of 2 days now.

EDIT: The issue is apparently related to the SWReveal. It deallocates instances before their lifecycle is over. Accepted the best solution, but the problem is related to SWReveal.


Solution

    1. Try using the MPMoviePlayerController instead of the AVPlayer, for simple solutions, the MPMoviePlayerController has an easier API.
    2. make the MPMoviePlayerController a global instance making it accessible through the whole app, and then initialize it when you need it.
    3. Try playing the videos locally first and check if it solves the problem