MPMoviePlayerController deprecated, what now?

user4545564 picture user4545564 · Apr 26, 2016 · Viewed 8.9k times · Source

So I have been searching for a solution now when MPMoviePlayerController is getting deprecated. my current code works fine:

moviePlayer = MPMoviePlayerController(contentURL: receivedURL)
    moviePlayer!.movieSourceType = MPMovieSourceType.Unknown
    moviePlayer!.view.frame = view.bounds
    moviePlayer!.scalingMode = MPMovieScalingMode.AspectFill
    moviePlayer!.controlStyle = MPMovieControlStyle.None
    moviePlayer!.shouldAutoplay = true

    view.addSubview((moviePlayer?.view)!)
    moviePlayer?.setFullscreen(true, animated: true)
    moviePlayer!.play()

I record a video, and once I'm done recording, it will be played back with the code above in a new view. But as I understand MPMoviePlayerController is deprecated in iOS9 and I can't find any solution working like the code above. I understand I need to user AVPlayer and AVPlayerViewController.

I have tried this and many other solutions that looks like them. But it just won't work like I want it in the code above.

I just want to record a video, and have it played back in a new view, exactly like snapchat.

Please help me

ADDED ADDITIONAL INFO:

So when I try to fix it with this (the accepted answer) or this solution (AVPlayer), the view is blank. nothing is shown.

var player:AVPlayer!
    let avPlayerLayer:AVPlayerLayer = AVPlayerLayer(player: player)
    avPlayerLayer.frame = CGRectMake(50,50,100,100)
    self.view.layer.addSublayer(avPlayerLayer)
    player = AVPlayer(URL: receivedURL)
    player.play()

And If i try with the AVPlayerViewController which I had to modify:

let player = AVPlayer(URL: receivedURL)
    let playerViewController = AVPlayerViewController()
    playerViewController.player = player
    dispatch_async(dispatch_get_main_queue(), {
        self.presentViewController(playerViewController, animated: true) {
            playerViewController.player?.play()
        }
    })

this happens, where nothing is shown. enter image description here

Answer

Olga Nesterenko picture Olga Nesterenko · Apr 26, 2016
var player:AVPlayer!
let avPlayerLayer:AVPlayerLayer = AVPlayerLayer(player: player)
avPlayerLayer.frame = CGRect(x:50,y:50,width:100,height:100)
self.view.layer.addSublayer(avPlayerLayer)
player = AVPlayer(url: receivedURL)
player.play()

here you initialize your player AFTER adding it to AVPlayerLayer. try like this:

let player = AVPlayer(url: receivedURL)
let avPlayerLayer:AVPlayerLayer = AVPlayerLayer(player: player)
avPlayerLayer.frame = CGRect(x:50,y:50,width:100,height:100)
self.view.layer.addSublayer(avPlayerLayer)
player.play()