把你MPMoviePlayerController
放在一个单独的类中并加载它:
MoviePlayerViewController.h
#import <MediaPlayer/MediaPlayer.h>
@interface MoviePlayerViewController : UIViewController
@end
MoviePlayerViewController.m
#import "MoviePlayerViewController.h"
MPMoviePlayerViewController *movieController;
@interface MoviePlayerViewController ()
@end
@implementation MoviePlayerViewController
- (void)willEnterFullscreen:(NSNotification*)notification {
NSLog(@"willEnterFullscreen");
}
- (void)enteredFullscreen:(NSNotification*)notification {
NSLog(@"enteredFullscreen");
}
- (void)willExitFullscreen:(NSNotification*)notification {
NSLog(@"willExitFullscreen");
}
- (void)exitedFullscreen:(NSNotification*)notification {
NSLog(@"exitedFullscreen");
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)playbackFinished:(NSNotification*)notification {
NSNumber* reason = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
switch ([reason intValue]) {
case MPMovieFinishReasonPlaybackEnded:
[self dismissModalViewControllerAnimated:YES];
break;
case MPMovieFinishReasonPlaybackError:
break;
case MPMovieFinishReasonUserExited:
[self dismissModalViewControllerAnimated:YES];
break;
default:
break;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterFullscreen:) name:MPMoviePlayerWillEnterFullscreenNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willExitFullscreen:) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enteredFullscreen:) name:MPMoviePlayerDidEnterFullscreenNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitedFullscreen:) name:MPMoviePlayerDidExitFullscreenNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
NSString *videoName = @"Videoname";
NSString *filepath = [[NSBundle mainBundle] pathForResource:videoName @"movietype"];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
movieController = [[MPMoviePlayerViewController alloc] initWithContentURL:fileURL];
[movieController.view setFrame:CGRectMake(0, -20, 320, 480)];
[self.view addSubview:movieController.view];
[movieController.moviePlayer play];
}
视图控制器.m
MoviePlayerViewController *player = [[MoviePlayerViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:player animated:YES];
它能做什么:
MoviePlayerViewController
是一个自定义类,它加载MPMoviePlayerController
一个视频。在viewDidLoad
方法中(或任何你想要的地方)你加载MoviePlayerViewController
. ( [self presentModalViewController:animated]
).... 这样做的好处是,您的主类不会因moviecrap/定义而重载,并且您可以MoviePlayerViewController
在完成时轻松关闭它,使用通知来检查它是否已停止。如果它已停止:
[self dismissModalViewControllerAnimated:YES];
希望这可以帮助!