在iOS SDK9中廢棄了之前用來播放視頻的MPMoviePlayerController,改成了AVPlayer。 使用AVPlayer需要導入AVKit.framework這個框架,并且在需要使用的ViewController中添加和兩個頭文件。
通過網絡請求下載網絡視頻到ios的沙盒中,之后獲取到該視頻在沙盒中的url,就可以通過AVPlayer播放該視頻了。代碼如下。
先獲取沙盒中Documents的路徑。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
假設存儲在Documents中的文件名為test.mp4,得到視頻文件的絕對路徑。
NSString *fullPath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"test.mp4"];
使用AVPlayer來播放該視頻。
NSURL *videoURL = [NSURL fileURLWithPath:fullPath];
AVPlayer *player = [AVPlayer playerWithURL:videoURL];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
playerLayer.frame = self.view.bounds;
[self.view.layer addSublayer:playerLayer];
[player play];
注意上面代碼中生成videoURL使用的是NSURL的fileURLWithPath,而不是URLWithString,前者用來訪問本地視頻,后者用來訪問網絡視頻。