Bird
0
0

Identify the error in this Swift code for sending a POST request with JSON body:

medium📝 Debug Q14 of 15
iOS Swift - Networking
Identify the error in this Swift code for sending a POST request with JSON body:
var request = URLRequest(url: URL(string: "https://api.example.com")!)
request.httpMethod = "POST"
let json = ["key": "value"]
request.httpBody = try? JSONSerialization.jsonObject(with: json)
AhttpMethod should be lowercase "post"
BMissing setting Content-Type header to application/json
CUsing JSONSerialization.jsonObject instead of data(withJSONObject:)
DURLRequest initialization is incorrect
Step-by-Step Solution
Solution:
  1. Step 1: Check JSON serialization method

    jsonObject(with:) parses JSON data to object; to create JSON data from object, use data(withJSONObject:).
  2. Step 2: Confirm other parts

    Content-Type header missing is an issue but not the main error causing failure here.
  3. Final Answer:

    Using JSONSerialization.jsonObject instead of data(withJSONObject:) -> Option C
  4. Quick Check:

    Wrong JSON method used = D [OK]
Quick Trick: Use data(withJSONObject:) to create JSON data, not jsonObject(with:) [OK]
Common Mistakes:
  • Confusing jsonObject(with:) with data(withJSONObject:)
  • Forgetting Content-Type header
  • Incorrect URLRequest initialization

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes