Search code examples
ioscocoa-touchmpmovieplayercontrollernstimerviewdidload

Weird behavior running MPMoviePlayerController in viewDidLoad


I'm using the MediaPlayer framework to play a pretty sizeable movie (~200 MB) as soon as my application is launched. When I attempt to play the video in my viewDidLoad, breakpoints indicated that the view was added however the video did not show up on the device.

I then set up a button to confirm that the video worked at all. Running the IBAction from the button showed no problems.

So then I was stumped. And I wondered if it had anything to do with the fact that the video was being called as soon as the application was launched. So I added a NSTimer with a delay of five seconds to the viewDidLoad call. Lo and behold, it worked fine. Can anyone shed any light on to why the video won't play unless there is an initial delay? Code below.

- (void)viewDidLoad {
      NSTimer *currentTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(playMovie) userInfo:nil repeats:NO];
        [[NSRunLoop mainRunLoop] addTimer:currentTimer forMode:NSRunLoopCommonModes];
      [super viewDidLoad];
}

-(IBAction)playMovie
{  
    NSString *filepath   =   [[NSBundle mainBundle] pathForResource:@"Speed" ofType:@"mov"];  
    NSURL    *fileURL    =   [NSURL fileURLWithPath:filepath];  
    MPMoviePlayerController *moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];  

    [[NSNotificationCenter defaultCenter] addObserver:self  
                                             selector:@selector(moviePlaybackComplete:)  
                                                 name:MPMoviePlayerPlaybackDidFinishNotification  
                                               object:moviePlayerController];  

    [self.view addSubview:moviePlayerController.view];  
    moviePlayerController.fullscreen = YES;  
    [moviePlayerController play]; 
}  

Solution

  • Try playing the movie in viewDidAppear: instead of viewDidLoad. At the point viewDidLoad is called, the view is not yet in the view hierarchy. You could still create the MPMoviePlayerController in viewDidLoad, just don't play it until the view actually appears.