【问题标题】:Save file to temp directory, then call back the url from that temp directory将文件保存到临时目录,然后从该临时目录回调 url
【发布时间】:2017-02-24 14:01:17
【问题描述】:

我正在使用此代码让用户将视频下载到临时目录:

@IBAction func startDownload(_ sender: UIButton) {
    let videoImageUrl = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4"


    DispatchQueue.global(qos: .default).async {
        let url = NSURL(string: videoImageUrl);
        let urlData = NSData(contentsOf: url! as URL);
        if(urlData != nil)
        {
            let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
            let filePath="\(documentsPath)/tempFile.mp4";
            DispatchQueue.main.async {
                urlData?.write(toFile: filePath, atomically: true);
                PHPhotoLibrary.shared().performChanges({
                    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: NSURL(fileURLWithPath: filePath) as URL)
                }) { completed, error in
                    if completed {
                        print("Video is saved!")
                    }
                }
            }
        }
    }
}

否则,当点击按钮下载时,应用程序会在一段时间后冻结。

理想情况下,我希望将文件“临时”保存到应用程序中,而不是出现在手机的照片库中。

这怎么可能?

那么,有没有办法从那个临时目录中回调文件?

在这个过程中如何实现?

非常感谢大家!

---- 编辑 ---

 @IBAction func startDownload(_ sender: UIButton) {


        let urlString = "\(posts[selectedIndexPath].link)"

        DispatchQueue.global(qos: .default).async(execute: {
            //All stuff here

            print("downloadVideo");
            let url=NSURL(string: urlString);
            let urlData=NSData(contentsOf: url! as URL);

            if((urlData) != nil)
            {
                let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

                let fileName = urlString as NSString;

                let filePath="\(documentsPath)/\(fileName.lastPathComponent)";

                DispatchQueue.main.async(execute: { () -> Void in

                    print(filePath)
                    urlData?.write(toFile: filePath, atomically: true);
                    print("video Saved to document directory of app");
                })
            }
        })


}


@IBAction func playDownload(_ sender: UIButton) {


        let urlString = "\(posts[selectedIndexPath].link)"

        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let fileName = urlString as NSString;
        let filePath="\(documentsPath)/\(fileName.lastPathComponent)";

        let fileURL = NSURL.init(fileURLWithPath: filePath)
        let request = NSURLRequest.init(url: fileURL as URL)


    print(fireURL)
    print("video called from document directory of app");

        // creating webView to play video, you can use player as per requirement
        let webView = UIWebView.init(frame: CGRect.init(x: 0, y: 0, width: 320, height: 320))
        webView.loadRequest(request as URLRequest)
        self.view.addSubview(webView)



}

在控制台中这是我得到的:

 /var/mobile/Containers/Data/Application/0A2D4FC0-F001-4711-916C-86C34CC5B71A/Documents/Cabin_Mono_4K_60fps.mp4?alt=media&token=32faeba5-3d9b-4090-9340-3e28986db5fa
video Saved to document directory of app

file:///var/mobile/Containers/Data/Application/0A2D4FC0-F001-4711-916C-86C34CC5B71A/DocumentsCabin_Mono_4K_60fps.mp4%3Falt=media&token=32faeba5-3d9b-4090-9340-3e28986db5fa

【问题讨论】:

  • 在 iOS 上这些都是非常琐碎的事情。但也许你应该从某种 iOS 教程开始,因为如果你每一步都在这里问一个问题,这将花费你很长时间。
  • 此外,SO 旨在帮助您修复错误或解决难题,而不是为您编写代码。
  • 嗨 Deadbeef,该代码确实可以将视频保存到我的照片库中 - 如何调用该文件已保存?如果您有任何指示,那就太好了,我不是要代码:)
  • 考虑使用downloadTask of URLSession。这几乎是您正在寻找的。从远程 URL 同步加载数据——甚至在后台线程上调度——无论如何都是不好的编程习惯。

标签: ios swift download temporary-files temporary-directory


【解决方案1】:

以下方法将视频保存到文档目录(特定于应用程序):

func downloadVideo()
{
    let urlString = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4"

    DispatchQueue.global(qos: .default).async(execute: {
        //All stuff here

        print("downloadVideo");
        let url=NSURL(string: urlString);
        let urlData=NSData(contentsOf: url! as URL);

        if((urlData) != nil)
        {
            let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

            let fileName = urlString as NSString;

            let filePath="\(documentsPath)/\(fileName.lastPathComponent)";

            let fileExists = FileManager().fileExists(atPath: filePath)

            if(fileExists){

                // File is already downloaded
            }
            else{

                //download
                DispatchQueue.main.async(execute: { () -> Void in

                    print(filePath)
                    urlData?.write(toFile: filePath, atomically: true);
                    print("videoSaved");
                })
            }
        }
    })
}

无论您想在哪里获取视频,都可以从以下相同的文档目录中读取它:

    func GetVideo() {

    let urlString = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4"

    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let fileName = urlString as NSString;
    let filePath="\(documentsPath)/\(fileName.lastPathComponent)";

    let fileURL = NSURL.init(fileURLWithPath: filePath)
    let request = NSURLRequest.init(url: fileURL as URL)


    // creating webView to play video, you can use player as per requirement
    let webView = UIWebView.init(frame: CGRect.init(x: 0, y: 0, width: 320, height: 320))
    webView.loadRequest(request as URLRequest)
    self.view.addSubview(webView)

}

【讨论】:

  • 嗨,Bhanupriya,非常感谢您的帮助!当我通过在 urlstring 中添加 url 来调用视频时,它可以完美地工作,例如 'sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4' 但是,当我尝试通过将字符串更改为 '"(posts[selectedIndexPath].link)"' 来动态调用视频时它确实可以很好地在本地下载视频-但是当我想播放它时它不起作用。 ..(请参阅我编辑的代码)您对此有什么建议吗?会很棒!!
  • @tibewww 打印 urlString 并检查它是否获得正确的 url,如果它适合你,请投票并接受答案
  • 嗨,是的,视频是从好 URL 调用的,这有点奇怪,不知道为什么
  • 打印一份发给我,让我查一下
  • 谢谢Bhanupriya,似乎它没有从本地调用文件,我已经用更新的代码编辑了问题,调用打印+控制台消息,如果有帮助?非常感谢您的宝贵时间!
猜你喜欢
  • 2013-11-25
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
  • 2016-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多