iOS Swift Download and Open Files Using URL
Asked Answered
C

1

7

In my app I'm having files download open. Everything is done perfectly, But Problem is Files like zip,rar, tar files getting download but those files won't show up after completing download. Here is my tried code:

func DownloadDocumnt()
    {
        let sucessAlert = UIAlertController(title: "Download Files", message: "Download the file \(self.TopLbl.text!) to your mobile for offline access.", preferredStyle: UIAlertControllerStyle.alert)

        sucessAlert.addAction(UIAlertAction(title: "Start Download", style: UIAlertActionStyle.default, handler:  { action in

            self.view.makeToastActivity(message: "Downloading...")
            let fileURL = URL(string: "\(self.DocumentURL)")!
            let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
            let destinationFileUrl = documentsUrl.appendingPathComponent("\(self.TopLbl.text!)")
            let sessionConfig = URLSessionConfiguration.default
            let session = URLSession(configuration: sessionConfig)
            let request = URLRequest(url:fileURL)
            let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
                if let tempLocalUrl = tempLocalUrl, error == nil
                {
                    if let statusCode = (response as? HTTPURLResponse)?.statusCode
                    {
                        print("Successfully downloaded. Status code: \(statusCode)")
                    }
                    do
                    {
                        if(FileManager.default.fileExists(atPath: destinationFileUrl.path))
                        {
                            try FileManager.default.removeItem(at: destinationFileUrl)
                            try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                            self.showFileWithPath(path: destinationFileUrl.path)
                            self.view.hideToastActivity()
                        }
                        else
                        {
                            try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                            self.showFileWithPath(path: destinationFileUrl.path)
                            self.view.hideToastActivity()
                        }
                    }
                    catch (let writeError)
                    {
                        self.view!.makeToast(message: "Download Failed Try Again Later", duration: 2.0, position: HRToastPositionCenter as AnyObject)
                        print("Error creating a file \(destinationFileUrl) : \(writeError)")
                    }
                }
                else
                {
                    self.view!.makeToast(message: "Download Failed Try Again Later", duration: 2.0, position: HRToastPositionCenter as AnyObject)
                    print("Error took place while downloading a file. Error description");
                }
            }
            task.resume()
        }))
        sucessAlert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler:  { action in

        }))
        self.present(sucessAlert, animated: true, completion: nil)
    }

After completing download it will automatically show that download files Code here:

//Show Downloaded File
    func showFileWithPath(path: String)
    {
        let isFileFound:Bool? = FileManager.default.fileExists(atPath: path)
        if isFileFound == true
        {
            let viewer = UIDocumentInteractionController(url: URL(fileURLWithPath: path))
            viewer.delegate = self
            viewer.presentPreview(animated: true)
        }
    }

Zip,rar,tar,gz files are getting download but it won't show downloaded files.

Castello answered 17/5, 2017 at 9:2 Comment(2)
I am using same code, and .zip file is open easily .Oid
thanks for the code it help me a lotBlastosphere
H
0

Have you specified what kind of document you are trying to open? As I guessed "self.TopLbl.text" must end up with file extension.

I wanted to open a file ".docx" extension and it worked fine.

Hixon answered 30/8, 2019 at 9:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.