Search code examples
iosobjective-cavplayerhttp-live-streaming

ios Knowing when a hls livestream has played the last chunk


I do not have a problem a stream, but I do not know when it is buffering or when the stream has ended. Is there anyway to determine this in Objective-C. I have found solutions for audio and I even tried the AVPlayerItemDidPlayToEndTimeNotification but it does not work. Any suggestions?

    NSString *url = liveStream.stream[@"cdn"];

    dispatch_async(dispatch_get_main_queue(), ^{
        AVPlayerItem *playerItem = [[AVPlayerItem alloc]
                                    initWithURL:[NSURL URLWithString:url]];
         [_player replaceCurrentItemWithPlayerItem:playerItem];


        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];



        [_player play];
    });
}

-(void)itemDidFinishPlaying:(NSNotification *) notification {

}

Solution

  • In addition to the notification you're using, you should use KVO to observe the rate of the avPlayer, as well as the status of the avplayer's current AVPlayer item. From observing those properties, you can make a state machine of sorts where your player view controller knows what's going on, and can recover from various changes instate. There are various player states that you have to prepare for and recover from based on the properties that you observe.

    Here's an answer on how to check for buffering

    Here's an example of a complete AVPLayer

    And of course, here's apple's documentation on AVPlayer

    Here's the documentation on AVPlayerItem

    Lastly, here's the link on KVOController. You'll thank me for this later.