Muhammad Ali
Muhammad Ali

Reputation: 1

Video Downloading in swift and play in AVPlayer in swift

I am working in my to download video form the internet and play offline in AVPlayer but video is not playing

enter image description here

session.downloadTask(with: request) { (loaction, respone, error) in
        if error != nil{
            print(error?.localizedDescription ?? "Error Found")
        }else if let res = respone as? HTTPURLResponse ,res.statusCode == 200{
            if let document = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first{
                let desitnationurl = document.appendingPathExtension("mp4")
                if FileManager.default.fileExists(atPath: desitnationurl.path){
                    //MarK: file is create but video cannot playing...😥
                    let ur = URL(fileURLWithPath: desitnationurl.path)
                    let pay = AVPlayer(url: ur)
                    let controller = AVPlayerViewController()
                    controller.player = pay
                    DispatchQueue.main.async {
                        self.present(controller, animated: true, completion: {
                            pay.play()
                        })
                    }

                }else{
                    do{
                        try FileManager.default.copyItem(at: loaction!, to: desitnationurl)
                        self.URLoffile = desitnationurl.path
                        guard let ur = self.URLoffile else{
                            print("Error")
                            return}
                        print(ur)

                    }catch{

Upvotes: 0

Views: 2214

Answers (1)

Bhavesh Bansal
Bhavesh Bansal

Reputation: 101

I also faced the same issue, and after searching for hours, I was able to find the answer to this. After you have downloaded the video, you will have to use this code to play the downloaded file.

let baseUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

let assetUrl = baseUrl.appendingPathComponent("MyFileSaveName.mp4")
let avAsset = AVAsset(url: assetUrl)  // This is important
let playerItem = AVPlayerItem(asset: avAssest)
let player = AVPlayer(playerItem: playerItem)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true, completion: {
    player.play()
})

Upvotes: 1

Related Questions