create a network in swift

To create a network request in Swift, you can use the URLSession framework provided by Apple. The URLSession API allows you to make HTTP requests, handle responses, and manage session data.

Here's an example of an HTTP GET request in Swift using URLSession:

main.swift
if let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") {
    let session = URLSession.shared
    let task = session.dataTask(with: url, completionHandler: { data, response, error in
        if let error = error {
            print("Error: \(error)")
            return
        }
        guard let httpResponse = response as? HTTPURLResponse else {
            print("Invalid response")
            return
        }
        guard (200...299).contains(httpResponse.statusCode) else {
            print("HTTP response code: \(httpResponse.statusCode)")
            return
        }
        if let data = data, let jsonString = String(data: data, encoding: .utf8) {
            print(jsonString)
            // parse JSON data here
        }
    })
    task.resume()
}
783 chars
23 lines

This code sends a GET request to the specified URL and handles the response using a closure. The closure receives three parameters: the response data, the HTTP response object, and any error that occurred during the request.

You can use this code as a starting point to build out a more robust networking layer for your Swift app.

gistlibby LogSnag