Junior — Middle
What are the main components of a network request?
sobes.tech AI
Answer from AI
The main components of a network request in iOS include:
- URL — the address of the resource being requested.
- URLRequest — an object that contains information about the request: URL, HTTP method (GET, POST, etc.), headers, and body.
- URLSession — an object that manages the execution of network tasks.
- URLSessionTask — a task that performs the request and receives the response.
- Response — data received from the server, including status, headers, and body.
Example of a simple GET request using URLSession:
let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
// process the received data
print(String(data: data, encoding: .utf8) ?? "")
} else if let error = error {
print("Error: \(error.localizedDescription)")
}
}
task.resume()