【发布时间】:2017-10-16 15:24:54
【问题描述】:
在我的应用程序中,我正在打开文件下载。一切都做得很完美,但问题是 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)
}
下载完成后会自动显示下载文件的代码:
//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 文件正在下载,但不会显示下载的文件。
【问题讨论】:
-
我使用相同的代码,.zip 文件很容易打开。
-
感谢代码对我帮助很大
标签: swift3 zip nsfilemanager uidocumentinteraction rar