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

Save file to temp directory, then call back the url from that temp 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!")
                    }
                }
            }
        }
    }
}

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

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

这怎么可能?

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

这个过程是如何实现的?

非常感谢你们!

---- 编辑 ---

 @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)

}