How to check status of AVPlayer?

8.9k views Asked by At

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.

2

There are 2 answers

0
andreas On BEST ANSWER

I could not make it work with adding an observer on the currentItem as user @gabbler suggested.

However it helped using the notification center like this:

NSNotificationCenter.defaultCenter().addObserverForName(
    AVPlayerItemFailedToPlayToEndTimeNotification, 
    object: nil, 
    queue: nil, 
    usingBlock: { notification in
        self.stop()
    })

Note that stop() is a method in the same class which stops the stream as if a stop button were clicked.

1
Sean On

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")
}