I have a method to download a json from a url and it works correctly, I download the file and it prints the path where it was saved, but now I do not know how to implement a method to verify that if the file already exists, it does not it will be downloaded again and if not, enter the download method, I would also like to change the path where the file is saved from. I hope you can help me, Thanks.
I leave what I have.
================================================================================================= ==============================
import UIKit
class ViewController: UIViewController {
//Create URL to the source file you want to download
let fileURL = URL(string: "http://10.32.14.124:7098/Servicio.svc/getCentralesMovilJSON/")
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func descargar() {
//agregar al destino el archivo
let destinationFileUrl = documentsUrl.appendingPathComponent("centrales.json")
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 {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
print(destinationFileUrl)
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
}
}
task.resume()
}
}