fetch data in swift

To fetch data in Swift, you can use the URLSession API provided by Apple. First, you need to create a URL object from the endpoint you want to fetch data from. Then you can create a data task from the URLSession and start it. Once the data task is completed, you can handle the response data in the completion handler. Here's an example:

main.swift
let url = URL(string: "https://example.com/data.json")!

let task = URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data else {
        print("Error fetching data: \(error?.localizedDescription ?? "Unknown error")")
        return
    }
    
    // handle the response data here
    print(String(data: data, encoding: .utf8)!)
}

task.resume()
382 chars
14 lines

In this example, we create a URL object from https://example.com/data.json. Then we create a data task with URLSession.shared, which is a shared instance of URLSession. We pass the URL to the data task and specify a completion handler. In the completion handler, we check if there's an error fetching data. If there's no error, we print the response data as a string. Finally, we resume the data task to start fetching data.

gistlibby LogSnag