How to play video file from documentdirectory using avplayer

Viewed 7484

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()

    }
3 Answers

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)
Related