快速下载视频并在AVPlayer中快速播放

时间:2018-07-19 12:29:50

标签: swift

我正在努力从Internet下载视频并在AVPlayer中离线播放,但是视频无法播放

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{

1 个答案:

答案 0 :(得分:1)

我也遇到了同样的问题,经过几个小时的搜索,我找到了答案。下载视频后,您将必须使用此代码来播放下载的文件。

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