ios - 将文件保存到临时目录,然后从该临时目录回调 url

标签 ios swift download temporary-files temporary-directory

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

@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!")
                    }
                }
            }
        }
    }
}

否则,点击下载按钮时,App 会在一段时间后卡住。

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

这怎么可能?

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

在这个过程中如何实现?

非常感谢你们!

---- 编辑 ---

 @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

最佳答案

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

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)

}

关于ios - 将文件保存到临时目录,然后从该临时目录回调 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42440578/

相关文章:

ios - Swift AVAudioPlayer 不播放声音

ios - swift 3 - 推送通知的本地化不起作用

c# - 使用 C# 在 ASP.Net 中下载文件

php - 有没有办法用 PHP 从 Google Cloud Storage 下载文件?而不仅仅是阅读它

ios - 无法识别的字体系列 'Roboto' - React Native iOS

ios - 如果我正在执行 CGImageRelease(sourceImageRef), Objective-C ,应用程序崩溃

ios - for循环的返回字符串 - Swift 3

java - OpenGL ES 2.0 与 1.1

iphone - 在 CoreBluetooth.framework 中实现读/写特性

javascript - 如何在 jQuery AJAX 成功时强制下载文件?