Bird
0
0

Which Swift code snippet correctly handles encoding the request and decoding the response?

hard📝 Application Q8 of 15
iOS Swift - Networking
You want to send a POST request with a JSON body containing user info and receive a JSON response with a token. Which Swift code snippet correctly handles encoding the request and decoding the response?
ASet httpBody to user dictionary directly, then decode response with JSONDecoder()
BConvert user dictionary to string, set httpBody, then parse response with JSONSerialization.jsonObject(with:)
CEncode user dictionary with JSONSerialization.data(withJSONObject:), set httpBody, then decode response data with JSONDecoder().decode(Token.self, from: data!)
DSend user dictionary as URL parameters, then decode response with JSONDecoder()
Step-by-Step Solution
Solution:
  1. Step 1: Encode request body

    Use JSONSerialization.data(withJSONObject:) to convert dictionary to Data for httpBody.
  2. Step 2: Decode JSON response

    Use JSONDecoder to decode response Data into Token struct.
  3. Final Answer:

    Encode with JSONSerialization.data, decode with JSONDecoder -> Option C
  4. Quick Check:

    Correct encode/decode = A [OK]
Quick Trick: Encode request with JSONSerialization, decode response with JSONDecoder [OK]
Common Mistakes:
  • Setting httpBody to dictionary directly
  • Using string instead of Data for httpBody
  • Parsing response incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes