send api in swift

To send an API request in Swift, you can use URLSession and its dataTask method to make a network request to a specific URL. You can then use JSONSerialization to convert the response data into JSON format.

Here's an example code snippet:

main.swift
let urlString = "https://example.com/api"
let url = URL(string: urlString)!
var request = URLRequest(url: url)
request.httpMethod = "GET" // or "POST", "PUT", "DELETE", etc.

let session = URLSession.shared
let task = session.dataTask(with: request) { data, response, error in
    guard error == nil else {
        print("Error: \(error!)")
        return
    }
    guard let data = data else {
        print("No data received")
        return
    }
    do {
        let jsonResponse = try JSONSerialization.jsonObject(with: data, options: [])
        print(jsonResponse)
    } catch let error {
        print("JSON parsing error: \(error)")
    }
}
task.resume()
664 chars
24 lines

In this example, we create a URL request with a URL to our API endpoint, set the request method to "GET", and then create a URLSession data task with that request. In the completion handler of the data task, we check for any errors, retrieve and verify the response data, and then use JSONSerialization to parse the data into a JSON object. Finally, we print the JSON response to the console.

You can customize the request URL, parameters, headers, and method as per your API requirements.

gistlibby LogSnag