The delegate method on AVContentKeySessionDelegate are not being called

738 views Asked by At

I'm attempting to play an encrypted HLS stream using AVContentKeySession, but do not achieve playback and am seeing "NSURLConnection finished with error - code -1002" in the logs. The delegate methods on AVContentKeySessionDelegate are not being called by AVFoundation.

I can play the same stream successfully if I set a resource loader on the media asset.

I attempt playback as follows

NSString *mediaUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"media_url"];
AVURLAsset *avUrlAsset = (AVURLAsset*)[AVAsset assetWithURL:[NSURL URLWithString: mediaUrl]];
AVContentKeySession  *contentKeySession = [AVContentKeySession contentKeySessionWithKeySystem:AVContentKeySystemFairPlayStreaming];
[_contentKeySession setDelegate:[[PlaybackContentKeySessionDelegate alloc] init] queue:dispatch_get_main_queue()];
[_contentKeySession processContentKeyRequestWithIdentifier:@"skd://my_asset_id" initializationData:nil options:nil];
[playbackContentKeySession.contentKeySession addContentKeyRecipient:avUrlAsset];
avUrlAsset.resourceLoader.preloadsEligibleContentKeys = true;

AVPlayerItem *avPlayerItem = [AVPlayerItem playerItemWithAsset:avUrlAsset];

AVPlayer *avPlayer = [[AVPlayer alloc] initWithPlayerItem:avPlayerItem];

self.avPlayerViewController.player = avPlayer;

__weak ViewController *vc = self;
[self presentViewController:self.avPlayerViewController animated:YES completion:^(){
    vc.avPlayerViewController.player play];
}];

where the delegate class is as follows. It is incomplete, but at this stage I just wish to see the delegate method being called.

@interface PlaybackContentKeySessionDelegate : NSObject<AVContentKeySessionDelegate>

@end

- (void)contentKeySession:(nonnull AVContentKeySession *)session didProvideContentKeyRequest:(nonnull AVContentKeyRequest *)keyRequest {
    NSLog(@"contentKeySession");
}

@end

However, I am seeing the error message mentioned above. Note that if I set up a valid resourceLoader which can fetch the keys, playback proceeds with no problems.

1

There are 1 answers

1
mm_857 On

For anyone else that comes across something like this: the issue was that the ContentKeySession holds the delegate as a weak reference, as is conventional for the delegate pattern, so it was getting cleaned up. I kicked myself when someone spotted it!