How to play video using the fileURL

Viewed 1033

I am able to fetch the output file URL like below using custom video recorder.

file:///var/mobile/Containers/Data/Application/5EB769B8-193F-4C9F-982A-48892333A8F0/Documents/2018-Oct-31%2012:16:54output.mov

I need to play that video using AVPlayerViewController. I am using the below code for playing video in my viewcontroller. But it is not working. Could anyone guide me to do this task?

func pathVideo()

{


 if let path = Bundle.main.path(forResource: "file:///var/mobile/Containers/Data/Application/5EB769B8-193F-4C9F-982A-48892333A8F0/Documents/2018-Oct-31%2012:16:54output.mov", ofType: "mov", inDirectory: "file:///var/mobile/Containers/Data/Application/5EB769B8-193F-4C9F-982A-48892333A8F0/Documents/2018-Oct-31%2012:16:54output.mov")

 {


    let video  = AVPlayer(url: URL(fileURLWithPath: path))



    let playerViewController = AVPlayerViewController()


    playerViewController.player = video

    present(playerViewController, animated: true, completion:
    {

        video.play()

    })

    }

}
3 Answers

Here a couple of things wrong with your code. As you mentioned you have video placed in your application document directory(by seeing your video file path) so you can't get the path by calling the Bundle.main.path the method. It is used to retrieve the path of application local bundle resources (Files which you placed before the building application). More information about bundle class

So you have to access the document directory something like that.

let documentsPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! //This piece of code will return path of document directory."
let videoPath = documentsPath.appendPathComponent("2018-Oct-31%2012:16:54output.mov").path //Append your video name so that complete path could be prepared and access path property.

Now you can use this video path and pass to URL

let video  = AVPlayer(url: URL(fileURLWithPath: videoPath))

I think you have got my point and I hope it may help you to fix the code.

Note: The code snippet I have written is compatible with Swift 4.0 so you might be required some changes in the first two lines.

Try declaring let playerViewController = AVPlayerViewController() at class scope not in method's scope. My guess is, it gets deallocated.

And again Kamarshad's point is right. You should retrieve the URL from fileManager not from application Bundle

I’m not all that tech smart and I’m not even sure why I received this, sorry I’m on my cell phone n I know I’ve been hacked by a Mac OS device that somehow keeps signing in every single time I sign in on a gmail acct. I get the message stating that a Mac device has signed in at the precise moment I’m signing in on my phone into a specific gmail acct. When I signed out of a bunch of accounts I received a message saying “let this Mac device sign into your Google accounts” idk what’s going on or what this is

Related