
整個做法可以濃縮成一句話:找一個控制器專門負責播放影片,把它設為視窗的根視圖,播放結束後再切換到真正的首頁。適合品牌開場動畫這類場合。
新增 AnimationViewController,記得先引入系統庫 <MediaPlayer/MediaPlayer.h>,然後宣告播放器屬性:
@property (nonatomic, strong) MPMoviePlayerController *moviePlayer;
在懶加載中完成所有設定:
-(MPMoviePlayerController *)moviePlayer {
if (!_moviePlayer) {
_moviePlayer = [[MPMoviePlayerController alloc] init];
[_moviePlayer.view setFrame:self.view.bounds];
_moviePlayer.movieSourceType = MPMovieSourceTypeFile; // 播放本地檔案
_moviePlayer.controlStyle = MPMovieControlStyleNone; // 隱藏播放控制項
[self.view addSubview:_moviePlayer.view];
// 監聽播放結束
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playFinsihed)
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];
}
return _moviePlayer;
}
在 .h 中對外公開影片路徑與播放結束的 callback:
@property (nonatomic, copy) NSString *moviePath; @property (nonatomic, copy) void (^playFinished)();
收到通知後,記得移除 observer 並呼叫 callback,把控制權交還給 App。
- (AnimationViewController *)animationViewController {
if (!_animationViewController) {
_animationViewController = [[AnimationViewController alloc] init];
_animationViewController.moviePath =
[[NSBundle mainBundle] pathForResource:@"V" ofType:@"mp4"];
_animationViewController.playFinished = ^{
UINavigationController *rootNav = [[UINavigationController alloc]
initWithRootViewController:[[ViewController alloc] init]];
[UIApplication sharedApplication].keyWindow.rootViewController = rootNav;
};
}
return _animationViewController;
}
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.rootViewController = self.animationViewController;
[self.window makeKeyAndVisible];
return YES;
}
一開始 pathForResource: 一直回傳 nil,檢查後才發現是 mp4 沒有被正確加入 bundle。把資源整理進一個名為 Resource 的資料夾(並確認 Xcode 勾選了 target membership)後就正常了。
另外要提醒的是,MPMoviePlayerController 在 iOS 9 之後已被標記為 deprecated,新專案建議改用 AVPlayer 搭配 AVPlayerLayer,並監聽 AVPlayerItemDidPlayToEndTimeNotification 來取代上述通知,API 才不會在未來的系統版本中失效。
影片啟動頁的實作門檻很低,真正需要拿捏的是時機:影片必須在 didFinishLaunchingWithOptions 階段就能顯示,且要在結束後準時交接給首頁,否則容易出現黑畫面或閃屏。有需要的人可以參考上面的流程動手試試。