AVPlayerLayer existing even after the viewDidDisappear method call in iOS

372 Views Asked by At

In my application, I'm using AVPlayer to play a YouTube video with the help of HCYoutubeParser library.

My question is, when I load a new view controller I still can hear the sound of the played video file.

I tried to load the next view two different methods but still having the same result.

Method 1

FourthViewController *fourthViewCont = [self.storyboard instantiateViewControllerWithIdentifier:@"FourthViewControllerID"];
[self.navigationController pushViewController:fourthViewCont animated:YES];

Method 2

Using storyboard segue

I can get rid of this problem by adding following code inside the viewDidDisappear method

[avPlayerLayer removeFromSuperlayer];
avPlayerLayer = nil;

But what I need to know is even when the view is disappeared why the avPlayerLayer instance having a reference?

I am adding the player layer like below

[_playerContainerView.layer addSublayer:avPlayerLayer];

_playerContainerView is not the main UIView but a UIView located inside the main UIView.

I have declared AVPlayerLayer variable in the class extension like below

@interface PlayerViewController ()
{
    AVPlayerItem *avPlayerItem;
    AVPlayerLayer *avPlayerLayer;
}

and also AVPlayer and the container view has weak refeences

@property (weak, nonatomic) AVPlayer *avPlayer;
@property (weak, nonatomic) IBOutlet UIView *playerContainerView;

My confusion increase more with the following scenario, which is when I going back from PlayerViewController to my previous view, the player stops correctly without any background audio sound.

Can anybody explain this situation?

Edit :

This is how I initialized the AVPlayer and AVPlayerLayer

_avPlayer = [AVPlayer playerWithPlayerItem:avPlayerItem];
avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:_avPlayer];

After these initialization I added sublayer and all these codes inside the completion block

[HCYoutubeParser h264videosWithYoutubeURL:youtubeUrl completeBlock:^(NSDictionary *videoDictionary, NSError *error) {
// ...
0

There are 0 best solutions below