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

时间:2017-02-24 14:01:17

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

我使用此代码将用户的视频下载到临时的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,不要出现在Mobile的图书馆里。

这怎么可能?

然后,有没有办法从该临时目录回调文件?

在此过程中如何实现这一目标?

非常感谢你们!

----编辑---

 @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

1 个答案:

答案 0 :(得分:0)

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

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)

}