'How to play video file from documentdirectory using avplayer

I am creating video player application in ios,if i store mp4 file in bundle resource or if i stream url it is working fine but if i store a file in document direcory and i am trying to play with avplayer it is not playing should i handle differently with offline file in document directory

code:

let fileManager = FileManager()
        let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/myvideo.mp4"))
   self.playVideo(filePath: destinationURLForFile.path)


   func playVideo(filePath:String)
    {
        var playerItem = AVPlayerItem.init(url:URL.init(string: filePath)!)

        var player = AVPlayer(playerItem: playerItem)
        var playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = self.view.frame
        self.view.layer.addSublayer(playerLayer)
        player.play()

    }


Solution 1:[1]

swift 3/4 100%%%%%%% workable

Recorder open video camera

@IBAction func RecordAction(_ sender: Any) {

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
            print("CameraAvailable")
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .camera
            imagePicker.mediaTypes = [kUTTypeMovie as String]
            imagePicker.allowsEditing = false
            imagePicker.showsCameraControls = true

            self.present(imagePicker,animated: true, completion: nil)
        }

        else{
            print("CameraNotAvailable")
        }
    }

save to document directory

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        // recover video URL
        let url = info[UIImagePickerControllerMediaURL] as? URL
        // check if video is compatible with album
        let compatible: Bool = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum((url?.path)!)
        // save
        if compatible {
            UISaveVideoAtPathToSavedPhotosAlbum((url?.path)!, self, nil, nil)
            print("saved!!!! \(String(describing: url?.path))")

        }
        videopath = url //save url to send next function play video
        dismiss(animated: true, completion: nil)
    }
//   error
    func video(_ videoPath: String, didFinishSavingWithError error: Error?, contextInfo: UnsafeMutableRawPointer) {
    }

play video from Document directory

 @IBAction func playvideo(_ sender: Any)
    {
        let player = AVPlayer(url: videopath!)  // video path coming from above function

        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        self.present(playerViewController, animated: true) {
            playerViewController.player!.play()
        }
}

Solution 2:[2]

Try this, written in Swift 3.0,

let fm = FileManager.default
let docsurl = try! fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let path = docsurl.appendingPathComponent("myvideo.mp4")
playVideo(filePath: path)

func playVideo(filePath:String)
{
    var playerItem = AVPlayerItem(url: URL(fileURLWithPath: filePath)
    var player = AVPlayer(playerItem: playerItem)
    var playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.frame
    self.view.layer.addSublayer(playerLayer)
    player.play()

}

Solution 3:[3]

I tried several methods including the above, but found that the documents path changes for the app each time it is launched, which changes the first part of the URL.

This helped me to get the current location of my file:

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let playerItem = AVPlayerItem(url: URL(fileURLWithPath: documentsPath.appendingFormat("/\(clipId).mp4")))
player = AVPlayer(playerItem: playerItem)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Govind Wadhwa
Solution 2 AshokPolu
Solution 3 Pylyp Dukhov