How to check status of AVPlayer?

andreas picture andreas · Nov 13, 2014 · Viewed 7.9k times · Source

I thought that I could check the status of an AVPlayer simply by the property "rate".

This is how I create a player instance:

player = AVPlayer(URL: stream) // streaming from the internet
player!.play()

At some later point I would do something like this

println(player!.rate)

This is what I discovered:

  • In Simulator I get "0.0" in case the player is not running or "1.0" if it is running.
  • If I start the player but interrupt the internet connection it changes values from 1 to 0.
  • However, on my iPhone the property keeps value 1 even if I enter Airplane Mode?!

Do you have any idea why that happens and how I could check the stream condition otherwise?

I have tried an observer so far:

player!.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.New, context: nil)

But even the method "observeValueForKeyPath" does not get fired in my iPhone test case.

Answer

Sean picture Sean · Oct 25, 2015

Check out the Apple docs here and scroll to the "Key-Value Observing" section. Especially #3 in that section.

It helped me get my implementation to work. My resulting code looks like this:

//Global
var player = AVPlayer()

func setUpPlayer() {
    //...
    // Setting up your player code goes here
    self.player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions(), context: nil)
    //...
}

// catch changes to status
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    print("obsrved")
}