Release MPMoviePlayer when using a tabbarcontroller

398 views Asked by At

I'm using a tabbarcontroller in which one of the views has an MPMoviePlayer. It works fine, except that if I change tab, the movie doesn't stop and keeps playing in the background. Then if I try to tab back to the movie tab, it crashes.

I think the only code I have to release the MPMoviePlayer is when it's finished playing, but I want it to be released when I change views instead. Then if I go back to the Movie tab, we start fresh.

In my .h file have set up as:


import < UIKit/UIKit.h>

import < MediaPlayer/MediaPlayer.h>


@interface SecondViewController : UIViewController {
    MPMoviePlayerController *player;
}

@end  

and in my .m file have:


- (void)viewDidLoad {

 NSString *url = [[NSBundle mainBundle]
 pathForResource:@"vid"
 ofType:@"m4v"];

 player = [[MPMoviePlayerController alloc]
 initWithContentURL:[NSURL fileURLWithPath:url]];

 [[NSNotificationCenter defaultCenter]

 addObserver:self
 selector:@selector(movieFinishedCallback:)
 name:MPMoviePlayerPlaybackDidFinishNotification
 object:player];

 //--called when the movie view and then add it to the View window--
 player.view.frame = CGRectMake(10, 10, 300, 300);
 [self.view addSubview:player.view];

    //--play movie--
    [player pause];

    [super viewDidLoad];
}

//--called when the movie is done playing--
- (void) movieFinishedCallback:(NSNotification*) aNotification {
    MPMoviePlayerController *moviePlayer = [aNotification object];
    [[NSNotificationCenter defaultCenter]
     removeObserver:self
     name:MPMoviePlayerPlaybackDidFinishNotification
     object:moviePlayer];
    [moviePlayer.view removeFromSuperview];
    [player release];
}

Any suggestions? Thank you :)

1

There are 1 answers

0
JOM On

If you really want to release MPMoviePlayer at tab switch, then do it in viewWillDisappear or viewDidDisappear. Now it's left alive at background, as you described. When you come back to tab, you try to create it again.

Difficult to say what would be the exact reason for crash, there seems to be several possibilities. Next time write a "Why did this crash" question with a call stack.

Maybe you could think about just pause/resume, so you wouldn't need to reallocate new moviePlayer every time user changes tabs? Do alloc/release in viewDidLoad and viewDidUnload, but play/pause in viewWillAppear and viewWillDisappear.