Search code examples
swift2mpmovieplayercontrollermp4

Swift 2 - fileURLWithPath returns NIL


I am trying to load a video using MPMoviePlayerController. I have added the file in my project and also added to the Build Phase "Copy Bundle Resource".

When I call the function to open the video I can see that the path its printed out however, the app crashes on 'fileURLWithPath`.

What am I doing wrong? Are .mp4 flies playable?

 func firstView(){

        if let filePath  = NSBundle.mainBundle().pathForResource("firstVideo", ofType: "mp4") {

            print(filePath)
//PRINTS: /var/mobile/Containers/Bundle/Application/B93BB049-DA87-4D89-AEBE-A5C92C01726E/MyApp.app/firstVideo.mp4

            firstMoviePlayer!.contentURL = NSURL.fileURLWithPath(filePath) // fatal error
        }


        firstMoviePlayer!.repeatMode = .None
        firstMoviePlayer!.controlStyle = MPMovieControlStyle.Embedded

        firstMoviePlayer!.view.frame = FirstTimeVideoView.frame
        FirstTimeVideoView.addSubview(firstMoviePlayer!.view)

        firstMoviePlayer!.play()


    }

Solution

  • You just need to change:

    if let filePath  = NSBundle.mainBundle().pathForResource("firstVideo", ofType: "mp4") {
    
                print(filePath)
    //PRINTS: /var/mobile/Containers/Bundle/Application/B93BB049-DA87-4D89-AEBE-A5C92C01726E/MyApp.app/firstVideo.mp4
    
                firstMoviePlayer!.contentURL = NSURL.fileURLWithPath(filePath) // fatal error
            }
    

    TO:

    if let filePath  = NSBundle.mainBundle().URLForResource("firstVideo", ofType: "mp4") {
    
                print(filePath)
    //PRINTS: /var/mobile/Containers/Bundle/Application/B93BB049-DA87-4D89-AEBE-A5C92C01726E/MyApp.app/firstVideo.mp4
    
                firstMoviePlayer!.contentURL = NSURL.fileURLWithPath(filePath) // fatal error
            }