iOS Swift使用URL下载和打开文件

Kav*_*gam 6 zip rar nsfilemanager uidocumentinteraction swift3

在我的应用中,我正在打开文件下载。一切都做得很完美,但是问题是zip,rar,tar文件等文件正在下载,但下载完成后这些文件将不会显示。这是我尝试的代码:

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)
    }
Run Code Online (Sandbox Code Playgroud)

完成下载后,它将自动在此处显示该下载文件的代码:

//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)
        }
    }
Run Code Online (Sandbox Code Playgroud)

Zip,rar,tar,gz文件正在下载,但不会显示下载的文件。

小智 0

您是否指定了要打开的文档类型?正如我猜测的那样,“self.TopLbl.text”必须以文件扩展名结尾。

我想打开一个扩展名为“.docx”的文件,它工作得很好。