How to check the status of AVPlayer?

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

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) 

Here is what I discovered:

  • In Simulator, I get β€œ0.0” if the player is down or β€œ1.0” if it is running.
  • If I start the player, but interrupted the Internet connection, it will change the values ​​from 1 to 0.
  • However, on my iPhone, the property retains the value 1, even if I enter airplane mode ?!

Do you have an idea why this is happening and how can I check the flow condition otherwise?

I have already tried an observer:

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

But even the "observValueForKeyPath" method does not start in my iPhone test case.

+6
source share
2 answers

I could not get it to work with adding an observer to currentItem, as the user @gabbler suggested.

However, this helped to use the notification center as follows:

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

Note that stop () is a method in the same class that stops the thread, as if the stop button was pressed.

+2
source

Check out the Apple docs here and go to the < Key-Value Observing section. Especially # 3 in this section.

This helped me make my implementation work. My final code is as follows:

 //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") } 
+6
source

Source: https://habr.com/ru/post/978118/


All Articles