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:
Step 1: Encode request body
Use JSONSerialization.data(withJSONObject:) to convert dictionary to Data for httpBody.
Step 2: Decode JSON response
Use JSONDecoder to decode response Data into Token struct.
Final Answer:
Encode with JSONSerialization.data, decode with JSONDecoder -> Option C
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
Master "Networking" in iOS Swift
9 interactive learning modes - each teaches the same concept differently