NSURL *url = <#Asset URL#> // Create asset to be played asset = [AVAsset assetWithURL:url]; NSArray *assetKeys = @[@"playable", @"hasProtectedContent"];
// Create a new AVPlayerItem with the asset and an // array of asset keys to be automatically loaded playerItem = [AVPlayerItem playerItemWithAsset:asset automaticallyLoadedAssetKeys:assetKeys];
// Register as an observer of the player item's status property [playerItem addObserver:self forKeyPath:@"status" options:options context:&PlayerItemContext];
// Associate the player item with the player player = [AVPlayer playerWithPlayerItem:playerItem]; }
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context { // Only handle observations for the PlayerItemContext if (context != &PlayerItemContext) { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; return; }
if ([keyPath isEqualToString:@"status"]) { AVPlayerItemStatus status = AVPlayerItemStatusUnknown; // Get the status change from the change dictionary NSNumber *statusNumber = change[NSKeyValueChangeNewKey]; if ([statusNumber isKindOfClass:[NSNumberclass]]) { status = statusNumber.integerValue; } // Switch over the status switch (status) { caseAVPlayerItemStatusReadyToPlay: // Ready to Play break; caseAVPlayerItemStatusFailed: // Failed. Examine AVPlayerItem.error break; caseAVPlayerItemStatusUnknown: // Not ready break; } } }