send appid and nouce. validate response in swift

Here's a sample code that shows how to send App ID and nonce headers in a URLSession request in Swift, and how to validate the response:

main.swift
let urlString = "https://example.com/api"
guard let url = URL(string: urlString) else { return }

// create a URL session configuration
let config = URLSessionConfiguration.default
// add headers to the configuration
config.httpAdditionalHeaders = ["App-Id" : "yourAppId", "Nonce": "yourNonce"]

// create a URL session with the configured headers
let session = URLSession(configuration: config)

// create a URL request with the URL and HTTP method
var request = URLRequest(url: url)
request.httpMethod = "GET"

// send the request and handle the response
let task = session.dataTask(with: request) { (data, response, error) in
    // check for errors
    if let error = error {
        print("Error:", error.localizedDescription)
        return
    }
    
    // convert the response to HTTPURLResponse to check the status code
    guard let httpResponse = response as? HTTPURLResponse else {
        print("Invalid response")
        return
    }
    
    // validate the status code and data
    if (200..<300).contains(httpResponse.statusCode), let data = data {
        // handle the valid response
        print("Valid response received:", String(data: data, encoding: .utf8) ?? "")
    } else {
        // handle the invalid response
        print("Invalid response received:", httpResponse.statusCode)
    }
}

// start the task
task.resume()
1352 chars
42 lines

In the above code, we added the App ID and nonce headers to the URLSession configuration, so that they will be sent with every request sent using that configuration.

Then, we created a URL request with the desired URL and HTTP method (in this example, we used GET). We sent the request using a URLSession data task, and checked the response for errors and status code. Finally, we handled the valid and invalid responses accordingly.

gistlibby LogSnag