Bird
0
0

Identify the error in the following Swift code for loading an image from a URL:

medium📝 Debug Q14 of 15
iOS Swift - Networking
Identify the error in the following Swift code for loading an image from a URL:
let url = URL(string: "https://example.com/image.png")
URLSession.shared.dataTask(with: url!) { data, response, error in
  let image = UIImage(data: data!)
  imageView.image = image
}.resume()
AURL is not unwrapped safely
BUIImage cannot be created from data
CMissing call to resume()
DUpdating UI on background thread
Step-by-Step Solution
Solution:
  1. Step 1: Check thread usage for UI update

    UI updates must happen on the main thread, but here imageView.image is set inside the background thread closure.
  2. Step 2: Confirm other parts

    URL is force unwrapped (not safe but not the main error here), resume() is called, and UIImage creation is valid if data exists.
  3. Final Answer:

    Updating UI on background thread -> Option D
  4. Quick Check:

    UI updates must be on main thread [OK]
Quick Trick: Always update UI on main thread after data task [OK]
Common Mistakes:
  • Forgetting DispatchQueue.main.async for UI
  • Force unwrapping optionals unsafely
  • Not calling resume() on data task

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes