AVPlayerViewController with AVPlayer from NSURL

1.6k views Asked by At

I have AVPlayer that load video from url and put player inside AVPlayerViewController but I do not want to buffer and download video until user press play button. How should I do it?

var player: AVPlayer = AVPlayer(URL: nsurl)
var newVideoChunk: AVPlayerViewController = AVPlayerViewController()
                                newVideoChunk.player = player
1

There are 1 answers

0
Tommie C. On BEST ANSWER

AVPlayerViewController with AVPlayer from NSURL?

You will need to setup the video asset and create a playerItem with that NSURL based asset. Then you will need to add an observer to that playerItem (immediately):

self.playerItem?.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.New, context: Constants.AVPlayerStatusObservationContext)

From within the key value observer routine you can trap the context and call an external function:

   override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    //
    if context == Constants.AVPlayerStatusObservationContext {
        if (keyPath! == "status") {
            if (player!.status == AVPlayerStatus.ReadyToPlay) {
                print("ready")
                readyToPlay()

            } else if (player!.status == AVPlayerStatus.Failed) {
                // something went wrong. player.error should contain some information
            } else if (player!.status == AVPlayerStatus.Unknown) {
                print("unknown")
            }
        }
    }
}

If you only want to handle the buffering and download when the button is clicked then make sure you add the observer only within the button action method. This will work just as well with a file URL as an online URL.

Please check my sample gist for more information:

VideoPlayerViewController.swift