使用Alamofire下载视频,然后在AV播放器上播放

时间:2017-08-04 09:05:49

标签: ios swift3 alamofire avplayer nsdata

我使用以下代码从URL下载视频。它可以正常下载视频。

func downloadVideo(){

    Alamofire.request("https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4").downloadProgress(closure:{ (progress) in
    print(progress.fractionCompleted)
    self.progressView.progress = Float(progress.fractionCompleted)

    }).responseData{ (response) in
       print(response.result)
       print(response.result.value!)
       print(response.result.description)

        if let data = response.result.value {
            let obj = String(data: data, encoding: .utf8)
            let player = AVPlayer(url: URL(string: obj!)!)
            self.playerController.player = player
            self.addChildViewController(self.playerController)
            self.view.addSubview(self.playerController.view)
            self.playerController.view.frame = self.view.frame
            player.play()

        }

    }

但我想在AVPlayer

中播放此视频

我发现可能视频已下载为NSData。我是对的。? 任何人都可以帮助我如何在完成下载后播放此视频吗?

  

如果有人可以建议其他代码,那将是件好事   使用进度条下载视频,然后在Swift 3.0中播放。

TIA。

1 个答案:

答案 0 :(得分:5)

在搜索这些东西的几个小时之后

我想出了一种简单可靠的方法来转换URL中的NSData,以便AVPlayer可以播放

func downloadVideo(){

    Alamofire.request("https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4").downloadProgress(closure : { (progress) in
    print(progress.fractionCompleted)
    self.progressView.progress = Float(progress.fractionCompleted)
    }).responseData{ (response) in
       print(response)
       print(response.result.value!)
       print(response.result.description)
        if let data = response.result.value {

            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            let videoURL = documentsURL.appendingPathComponent("video.mp4")
            do {
                try data.write(to: videoURL)
                } catch {
                print("Something went wrong!")
            }
            print(videoURL)
            let player = AVPlayer(url: videoURL as URL)
            self.playerController.player = player
            self.addChildViewController(self.playerController)
            self.view.addSubview(self.playerController.view)
            self.playerController.view.frame = self.view.frame
            player.play()
        }
    }
}

您可以使用以下代码转换

if let data = response.result.value {

            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            let videoURL = documentsURL.appendingPathComponent("video.mp4")
            do {
                try data.write(to: videoURL) // Pass this videoURL to AVPlayer after Downloading Video it will be played.
                } catch {
                print("Something went wrong!")
            }
            print(videoURL)

根据请求, 这是完整实现的源代码。

Download Source Code

  

P.S: - 这是考虑一个演示。你们中的许多人会争辩说这个代码可以被优化并且可以做得更好,但是这是   是一个演示,您可以选择部分或全部取决于   你的要求