Hey everybody!
I'm trying to build an app where the user clicks the download button, then in background the app downloads the file and opens it directly in the default native application.
I download the file usind this code below. It return the local URL to the file.
@IBAction func downloadFile(_ sender: Any) {
downloadButton.isHidden = true
loading.isHidden = false
let url = URL(string: downloadURL!)!
URLSession.shared.downloadTask(with: url) { location, response, error in
guard let location = location, let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200 else { return }
let fileName = httpURLResponse.suggestedFilename ?? httpURLResponse.url?.lastPathComponent ?? url.lastPathComponent
let destination = FileManager.default.temporaryDirectory.appendingPathComponent(fileName)
do {
if FileManager.default.fileExists(atPath: destination.path) {
try FileManager.default.removeItem(at: destination)
}
try FileManager.default.moveItem(at: location, to: destination)
self.pushFile(destination)
} catch {
print(error)
}
}.resume()
}
And tried to open the file using this:
func pushFile(_ destination: URL) {
var finalURL = destination.absoluteString
DispatchQueue.main.async {
if let url = URL(string: finalURL) {
if #available(iOS 10, *){
UIApplication.shared.open(url)
}else{
UIApplication.shared.openURL(url)
}
}
}
How could i make it work?
Thank you for the help!