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

Objective-C How To Use observeValueForKeyPath To Check Status Of 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 甚至没有触发。我想知道是我做错了什么还是我的代码有问题?

理论上玩家的状态甚至可以在您的 KVO 注册之前改变,这意味着不会进行进一步的 KVO 回调。

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

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