You create a POST request in Swift with a JSON body. What is the expected behavior when the request is sent?
let url = URL(string: "https://example.com/api")! var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let json: [String: Any] = ["name": "John", "age": 30] request.httpBody = try? JSONSerialization.data(withJSONObject: json) let task = URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("Error: \(error)") } else if let data = data { print("Response data received") } } task.resume()
Check the httpMethod and httpBody properties of the URLRequest.
Setting httpMethod to "POST" and httpBody to JSON data sends a POST request with the JSON body to the server.
Choose the code snippet that correctly sets a JSON body for a POST request using URLRequest in Swift.
Look for the method that converts a dictionary to Data.
JSONSerialization.data(withJSONObject:) converts a dictionary to JSON Data. The other options are invalid or incorrect types.
Consider this Swift code creating a POST request with JSON body but missing a call. What is the effect?
let task = URLSession.shared.dataTask(with: request) { data, response, error in
// handle response
}Check how URLSession tasks start their work.
URLSession data tasks start only after calling resume(). Without it, the task is created but never runs.
Review this Swift code snippet. The POST request is sent but the server receives no JSON data. What is the likely cause?
var request = URLRequest(url: URL(string: "https://api.example.com")!)
request.httpMethod = "POST"
let json = ["user": "alice"]
request.httpBody = try? JSONSerialization.data(withJSONObject: json)
// Missing Content-Type header
let task = URLSession.shared.dataTask(with: request) { data, response, error in
// handle response
}
task.resume()Check the HTTP headers required for JSON data.
Without setting "Content-Type" to "application/json", the server may ignore or reject the JSON body.
You want to send a POST request with a JSON body. How should you handle possible errors during JSON encoding?
Think about safe error handling in Swift.
Using do-catch allows you to catch and handle JSON encoding errors properly before sending the request.