1

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.

mm_857
  • 171
  • 11

1 Answers1

0

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!

mm_857
  • 171
  • 11
  • I have not added separate delegate class, instead, implemented the delegate methods of AVContentKeySessionDelegate within my ViewController. My code snippet is: let asset = AVURLAsset(url: videoUrl) self.contentKeySession = AVContentKeySession(keySystem: .fairPlayStreaming) self.contentKeySession?.setDelegate(self, queue: DispatchQueue.main) self.contentKeySession?.addContentKeyRecipient(asset) But, the delegate methods are not being called. – Alen Alexander Jun 16 '20 at 05:47