check if a file has already been downloaded in swift 3

1

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()

}


}
    
asked by Diana Itzel Rodriguez Villalva 15.08.2017 в 23:15
source

1 answer

1

I was investigating and I managed to solve my doubt, now I can verify if my file exists, just send me the route where it is stored and if not, download it ....

here is my new code

import UIKit

class ViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()

 //llamar metodo para descargar json
        descargar()

}

//------------------Descargar archivo------------------------------------------------------------
func descargar() {


    //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!

    //agregar al destino el archivo
    let destinationFileUrl = documentsUrl.appendingPathComponent("centrales.json")

    //archivo existente???....................................................
    let fileExists = FileManager().fileExists(atPath: destinationFileUrl.path)

    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)

    let request = URLRequest(url:fileURL!)

    // si el archivo ya existe, no descargarlo de nuevo y enviar ruta de destino.........................................................................
    if fileExists == true {
        print("archivo existente")
        print(destinationFileUrl    )
    }

// si el archivo aun no existe, descargarlo y mostrar ruta de destino..........................................................................
    else{
        print("descargar archivo")



    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {
            // Success se ah descargado correctamente...................................
            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()

    }}

}
    
answered by 16.08.2017 в 19:12