如何在启动应用程序或使用完成按钮的viewdidload上播放视频?

时间:2012-08-03 23:38:49

标签: iphone ios ipad

通过调用在viewDidLoad方法中播放视频的函数,我已经能够在应用启动时成功播放视频。但是这样做,我无法看到“完成”按钮。如果我在一个按钮的帮助下调用相同的功能,似乎只显示“完成”按钮。我发布下面的代码。如何通过在viewDidLoad方法中调用相同的函数来完成此操作?我做错了什么?谢谢!

在我的viewcontroller.m文件中

- (void)viewDidLoad
{
      [super viewDidLoad];

      [self playMedia];
}

- (void) playMedia {

        //hide status bar first
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
        //resets again in playMediaFinished

        movieFile = [[NSBundle mainBundle] pathForResource:@"sec" ofType:@"mp4"];
        NSURL *url = [NSURL fileURLWithPath: movieFile];

        moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playMediaFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];

        moviePlayer.controlStyle = MPMovieControlStyleDefault;

        [moviePlayer setFullscreen:NO animated:YES];
        [self.view addSubview:moviePlayer.view];

        moviePlayer.controlStyle = MPMovieControlStyleDefault;

        CGAffineTransform transform = self.view.transform;

        [moviePlayer.view setFrame:CGRectMake(0, 0, 480, 320)];

        moviePlayer.shouldAutoplay = YES;

        NSLog(@"Should be playing Movie");

    }

- (void) playMediaFinished: (NSNotification*) theNotification {
       moviePlayer = [theNotification object];

        [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];

        if ([moviePlayer
             respondsToSelector:@selector(setFullscreen:animated:)])
        {
            [moviePlayer.view removeFromSuperview];
            [playerView removeFromSuperview];
            //reset status bar
            [[UIApplication sharedApplication] setStatusBarHidden:NO];
        }    
            NSLog(@"Should be DONE playing Movie");

    }

1 个答案:

答案 0 :(得分:3)

尝试使用viewDidAppear代替viewDidLoad执行此操作。考虑到您在主视图出现在屏幕上之前呈现视频,viewDidLoad中的视频导致意外行为并不奇怪。请记住,视图在实际可见之前已完成加载。