user4860206
user4860206

Reputation: 51

Objective-C How To Use observeValueForKeyPath To Check Status Of AVPlayer?

My current code is:

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

But for some reason, the observeValueForKeyPath isn't even firing. I was wondering if I did something wrong or if my code is wrong?

Upvotes: 2

Views: 3565

Answers (1)

Anurag
Anurag

Reputation: 141879

It is theoretically possible for the player's status to change even before your KVO registration which would mean that no further KVO callbacks are made.

I would suggest that you add the following option when performing the KVO registering - NSKeyValueObservingOptionInitial. This ensures that you will receive a callback for the initial value as well.

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

Upvotes: 3

Related Questions