IOS Swift Loading and Opening Files Using URL
In my application, I have file uploads open. Everything is done fine, but the problem is that files like zip, rar, tar are downloaded, but these files will not show up after the download is complete. Here is my tested 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)
}
Once the download is complete, it will automatically show that it is downloading files 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 downloaded but the downloaded files are not displayed.
+5
source to share