iosswiftdownloadtemporary-filestemporary-directory

Save file to temp directory, then call back the url from that temp directory


I'm using this code for user to download a video to a 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!")
                    }
                }
            }
        }
    }
}

Otherwise, when clicking on the button download, the App get frozen after sometime.

I'd like ideally the file to be save 'temporary' into the App, not to appear int he photolibrary of the Mobile.

How is this possible ?

Then, IS there a way to call back the file from that temporary directory ?

How this can be achieve in the process ?

Thanks a lot guys !

---- EDIT ---

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



}

in the console this is what I get:

 /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

Solution

  • Below method will save video to documents directory(specific for app) :

    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");
                    })
                }
            }
        })
    }
    

    Wherever you want to get video, you can read it from same document directory as below:

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