Search code examples
iphoneobjective-ciosxcodempmovieplayercontroller

MPMoviePlayerViewController disappears when home button is pressed


I’m creating my MPMoviePlayerViewController like so:

MPMoviePlayerViewController *playerView = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];
[self presentMoviePlayerViewControllerAnimated:playerView];

It works fine until I press the home button: that way, after I reopen the app, the player view controller is gone and I’m seeing the view controller I originally called it from. The player doesn’t disappear but simply pauses (as it should) if I double-press the home button, opening the multitasking panel.

So how do I prevent this from happening (closing and reopening the app should bring me back to playing the video)?

UPD: I noticed that the player doesn’t disappear if I close and reopen the app while the “Loading…” text is up. In that case, coming back to the app lets the player continue loading the video to eventually start playing. However closing the app after that (either when the video is playing or being paused) inevitably kills the player view controller…


Solution

  • Try like this:

     MPMoviePlayerViewController *playerView = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];
        playerView.view.frame = self.view.frame;
        [self presentMoviePlayerViewControllerAnimated:playerView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MPMoviePlayerDidExitFullscreen:) name:MPMoviePlayerDidExitFullscreenNotification object:nil];
        [[NSNotificationCenter defaultCenter]
         addObserver:self
         selector:@selector(playbackStateChanged:)
         name:MPMoviePlayerPlaybackStateDidChangeNotification
         object:moviePlayerController];
    
         [playerView.moviePlayer play];
    

    after that adding these two methods:

    - (void) movieFinishedCallback:(NSNotification*) aNotification 
    {
        moviePlayerController = [aNotification object];
        [moviePlayerController.moviePlayer stop];
        [[NSNotificationCenter defaultCenter] 
         removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification
         object:moviePlayerController];
        [moviePlayerController autorelease];
        NSLog(@"stopped?");
    }
    
    - (void)MPMoviePlayerDidExitFullscreen:(NSNotification *)notification
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name:MPMoviePlayerDidExitFullscreenNotification 
                                                      object:nil];
    
        [moviePlayerController.moviePlayer stop];
        MPMoviePlayerController *player = [notification object];
        [[NSNotificationCenter defaultCenter] 
         removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification
         object:player];
        [moviePlayerController dismissMoviePlayerViewControllerAnimated];
    }