Bird
0
0

You want to update a label's text after a network call completes. Which is the correct way to handle errors and update the UI safely in Swift?

hard📝 Application Q15 of 15
iOS Swift - Networking
You want to update a label's text after a network call completes. Which is the correct way to handle errors and update the UI safely in Swift?
URLSession.shared.dataTask(with: url) { data, response, error in
  // Handle error and update label
}
ACheck if error != nil, then update label text inside DispatchQueue.main.async block
BUpdate label text directly inside the completion handler without dispatching
CIgnore error and update label text on background thread
DUse try-catch inside the completion handler to update label
Step-by-Step Solution
Solution:
  1. Step 1: Handle threading and errors for UI updates

    Completion handlers run on background threads, so dispatch UI updates to main. First check if error != nil to handle failure (e.g., update label with error message), using DispatchQueue.main.async.
  2. Final Answer:

    Check if error != nil, then update label text inside DispatchQueue.main.async block -> Option A
  3. Quick Check:

    UI updates on main thread after error check [OK]
Quick Trick: Always update UI on main thread after error check [OK]
Common Mistakes:
  • Updating UI on background thread causing crashes
  • Ignoring error and updating UI blindly
  • Using try-catch incorrectly for async callbacks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes