Video Player崩溃pathForResource Swift iOS

时间:2015-01-26 07:27:46

标签: ios swift video 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)
        }
    }

}

enter image description here

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

  

致命错误:在展开Optional值时意外发现nil   原因路径是空的

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

确保视频资产文件具有目标会员资格'选中复选框。在左侧面板中选择资产'项目导航器',然后在右侧面板中的目标会员资格'确保选中项目方案名称旁边的复选框。