11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AVPlayerの再生状態をKVOで監視する

Posted at

動画が外部要因(バックグランド移動)によって停止されたりなんだりしたりした時にキー監視をする機会があったので
また、動画が再生されているかどうかは rate で判断されているとのこと

player.addObserver(self, forKeyPath: "rate", options: .New, context: nil)

まずは、KVOを設定

override func observeValueForKeyPath(keyPath: String?,
                                         ofObject object: AnyObject?,
                                                  change: [String : AnyObject]?,
                                                  context: UnsafeMutablePointer<Void>) {
        if keyPath == "rate" {
            if player?.rate = 0.0 {
                print("Pause")
            } else if player.?rate = 1.0 {
                print("Play")
            } else {
                print("Unknown")
            }
        }
    }

あとはViewControllerから脱出するときにKVOを削除する

player.removeObserver(self, forKeyPath: "rate")
11
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?