Objective-C如何使用observeValueForKeyPath检查AVPlayer的状态?

时间:2015-05-03 20:49:38

标签: objective-c avplayer

我目前的代码是:

...
    AVAsset *asset = [AVAsset assetWithURL:video];
    _videoDuration = CMTimeGetSeconds(asset.duration);

    AVPlayerItem *item = [[AVPlayerItem alloc] initWithAsset:asset];
    _player = [[AVPlayer alloc] initWithPlayerItem:item];
    _player.actionAtItemEnd = AVPlayerActionAtItemEndNone;

    [_player addObserver:self
              forKeyPath:@"status"
                 options:0
                 context:nil];
...


- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if (object == _player && [keyPath isEqualToString:@"status"]) {
        if (_player.status == AVPlayerStatusReadyToPlay) {
            NSLog(@"PLAYING");
        }
    }
}

但由于某种原因,observeValueForKeyPath甚至没有开火。我想知道我是否做错了或者我的代码是错的?

1 个答案:

答案 0 :(得分:2)

理论上,即使在您的KVO注册之前,玩家的状态也可能发生变化,这意味着不会再进行KVO回调。

我建议您在执行KVO注册时添加以下选项 - NSKeyValueObservingOptionInitial。这样可以确保您也会收到初始值的回调。

[_player addObserver:self
          forKeyPath:@"status"
             options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial)
             context:nil];