Search code examples
iosavfoundationkey-value-observingavplayer

Is KVO on AVPlayerItem.loadedTimeRanges possible?


Apples documentation alludes to it, but how do you set up key-value observation for the loadedTimeRanges property of AVPlayerItem? That property is an NSArray that doesn't change, so you can't just use playerItem addObserver:self forKeyPath:@"loadedTimeRanges ...

Or is there another way to get notifications or updates whenever this changes?


Solution

  • Actually, I'm using KVO for loadedTimeRanges without any trouble. Maybe you're just not setting the right options? The following is a very slight modification of some of the code in Apple's AVPlayerDemo, and it's working quite nicely for me.

    //somewhere near the top of the file
    NSString * const kLoadedTimeRangesKey   = @"loadedTimeRanges";
    static void *AudioControllerBufferingObservationContext = &AudioControllerBufferingObservationContext;
    
    
    - (void)someFunction
    {  
        // ...
    
        //somewhere after somePlayerItem has been initialized
        [somePlayerItem addObserver:self
                           forKeyPath:kLoadedTimeRangesKey
                              options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                              context:AudioControllerBufferingObservationContext];
    
        // ...
    }
    
    - (void)observeValueForKeyPath:(NSString*) path 
                      ofObject:(id)object 
                        change:(NSDictionary*)change 
                       context:(void*)context
    {
        if (context == AudioControllerBufferingObservationContext)
        {
            NSLog(@"Buffering status: %@", [object loadedTimeRanges]);
        }
    }