Unable to uninstall or stop AVPlayer

I have an AVPlayer that I upload to a new view whenever a link is clicked.

-(void)createAndConfigurePlayerWithURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType { self.playerItem = [AVPlayerItem playerItemWithURL:movieURL]; customControlOverlay = [[AFDetailViewController alloc] initWithNibName:@"AFMovieScrubControl" bundle:nil]; backgroundWindow = [[UIApplication sharedApplication] keyWindow]; [customControlOverlay.view setFrame:backgroundWindow.frame]; [backgroundWindow addSubview:customControlOverlay.view]; playerLayer = [AVPlayerLayer playerLayerWithPlayer:[AVPlayer playerWithPlayerItem:playerItem]]; [playerLayer.player play]; playerLayer.frame = customControlOverlay.view.frame; [customControlOverlay.view.layer addSublayer:playerLayer]; } 

The above code adds AVPlayer to my application and works great. I have a switch in my customControlOverlay nib that should remove the view and stop playing AVplayer.

 -(IBAction)toggleQuality:(id)sender { if (qualityToggle.selectedSegmentIndex == 0) { NSLog(@"HD"); [playerLayer.player pause]; [self.view removeFromSuperview]; } else if (qualityToggle.selectedSegmentIndex == 1) { NSLog(@"SD"); } } 

The view has been deleted correctly, but the player is still playing in the background. After testing the bit, the player will not respond to any code in the toggleQuality method, but the lines that I have when the checks are logged.

Any thoughts on what I'm doing wrong?

+6
source share
2 answers

I know this is an old question, but it might someday help someone.

Since playerLayer is added as a sublayer and not as a subview , it just needs to be removed from its super layer (instead of the supervisor) and the player should be set to nil, something like:

 /* not sure if the pause/remove order would matter */ [playerLayer.player pause]; // uncomment if the player not needed anymore // playerLayer.player = nil; [playerLayer removeFromSuperlayer]; 
+19
source

Here is the answer in Swift.

As @Paresh Navadiya and @Yoga said in the comments below the answer. The playerLayer must set to zero. playerLayer?.player = nil

Add code to viewWillDisappear:

 override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) player?.pause() // 1. pause the player to stop it playerLayer?.player = nil // 2. set the playerLayer player to nil playerLayer?.removeFromSuperlayer() // 3 remove the playerLayer from it superLayer } 
0
source

Source: https://habr.com/ru/post/916520/


All Articles