视频播放器崩溃 pathForResource Swift iOS

Video Player Crashes pathForResource Swift iOS

目前我尝试设置一个简单播放视频的小应用程序(仅供我女儿使用),但它总是在 "path"

上崩溃
import UIKit
import MediaPlayer

var moviePlayer : MPMoviePlayerController?

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        playVideo()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func playVideo() {

        let path = NSBundle.mainBundle().pathForResource("video", ofType:"mp4")
        let url = NSURL.fileURLWithPath(path!)
        moviePlayer = MPMoviePlayerController(contentURL: url)
        if let player = moviePlayer {
            player.view.frame = self.view.bounds
            player.prepareToPlay()
            player.scalingMode = .AspectFill
            self.view.addSubview(player.view)
        }
    }

}

崩溃发生在这里let path = NSBundle.mainBundle().pathForResource("video", ofType:"mp4")

fatal error: unexpectedly found nil while unwrapping an Optional value cause path is empty

您必须将 Build Phases 下 Xcode 目标中的视频添加到 Copy Bundle Resources

如果无法在包中找到文件,NSBundle pathForResource 函数会崩溃。要解决此问题,您可以执行以下操作:

let bundlePath:String = NSBundle.mainBundle().resourcePath!
let filePath:String = "\(bundlePath)/video.mp4"

确保视频资产文件已选中 'Target Membership' 复选框。 Select 左侧面板中的资产 'Project navigator',然后在 'Target Membership' 下的右侧面板中,确保选中项目方案名称旁边的复选框。