Bird
0
0

You want to fetch JSON data from a web API and decode it into a Swift struct using URLSession. Which sequence correctly performs this task?

hard📝 Application Q8 of 15
iOS Swift - Networking
You want to fetch JSON data from a web API and decode it into a Swift struct using URLSession. Which sequence correctly performs this task?
ACreate URL, start dataTask, decode JSON in completion handler, update UI on main thread
BCreate URL, decode JSON, start dataTask, update UI on background thread
CStart dataTask, create URL, decode JSON on main thread, update UI
DCreate URL, start dataTask, update UI directly in background thread
Step-by-Step Solution
Solution:
  1. Step 1: Create the URL

    Initialize a valid URL object for the API endpoint.
  2. Step 2: Start the data task

    Use URLSession.shared.dataTask(with:) to fetch data asynchronously.
  3. Step 3: Decode JSON in completion handler

    Use JSONDecoder to decode the data inside the completion handler.
  4. Step 4: Update UI on main thread

    Dispatch UI updates to the main thread using DispatchQueue.main.async.
  5. Final Answer:

    Create URL, start dataTask, decode JSON in completion handler, update UI on main thread correctly describes the proper sequence.
  6. Quick Check:

    Decode JSON in completion, update UI on main thread [OK]
Quick Trick: Decode JSON in completion, update UI on main thread [OK]
Common Mistakes:
  • Updating UI on background thread
  • Decoding JSON before data is fetched
  • Starting dataTask after decoding

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes