download a file from the internet in swift

To download a file from the internet in Swift, you can use the URLSession class. Here's an example code snippet to get you started:

main.swift
let url = URL(string: "https://www.example.com/myfile.txt")!

let session = URLSession.shared

let task = session.downloadTask(with: url) { localURL, response, error in
    if let localURL = localURL {
        if let data = try? Data(contentsOf: localURL) {
            // Do something with the downloaded data
        }
    } else if let error = error {
        print("Error downloading file: \(error)")
    }
}

task.resume()
428 chars
16 lines

In this example, we first create a URL object representing the file we want to download. Then, we create a URLSession object and use its downloadTask(with:completionHandler:) method to initiate the download. This method takes a completion handler that will be called when the download is complete.

Inside the completion handler, we check if the download was successful by ensuring that the localURL parameter is not nil. If it's not nil, we can assume the file was downloaded successfully, and we can load its contents into a Data object for further processing.

If there was an error during the download, we print an error message to the console.

Note that this code will download the file asynchronously, so you may want to use a dispatch group or semaphore to wait for the download to complete before proceeding with further processing.

related categories

gistlibby LogSnag