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:

let urlString = ""
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!)")
    guard let data = data else {
        print("No data received")
    do {
        let jsonResponse = try JSONSerialization.jsonObject(with: data, options: [])
    } catch let error {
        print("JSON parsing error: \(error)")
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