Bird
0
0

You want to load an image from a URL and display it in a UIImageView safely, handling errors and updating UI correctly. Which code snippet correctly achieves this?

hard📝 Application Q15 of 15
iOS Swift - Networking
You want to load an image from a URL and display it in a UIImageView safely, handling errors and updating UI correctly. Which code snippet correctly achieves this?
let url = URL(string: "https://example.com/image.png")
URLSession.shared.dataTask(with: url!) { data, response, error in
  if let data = data, let image = UIImage(data: data) {
    DispatchQueue.main.async {
      imageView.image = image
    }
  } else {
    print("Failed to load image")
  }
}.resume()
AThis code misses calling resume() on data task
BThis code correctly loads image and updates UI on main thread
CThis code updates UI on background thread
DThis code does not handle optional URL safely
Step-by-Step Solution
Solution:
  1. Step 1: Check for safe image loading and UI update

    The code unwraps data and image safely, then updates the UIImageView inside DispatchQueue.main.async, which is correct.
  2. Step 2: Verify error handling and task start

    It prints an error message if loading fails and calls resume() to start the task.
  3. Final Answer:

    This code correctly loads image and updates UI on main thread -> Option B
  4. Quick Check:

    Safe unwrapping + main thread UI update = correct [OK]
Quick Trick: Use DispatchQueue.main.async for UI updates after loading [OK]
Common Mistakes:
  • Not calling resume() to start task
  • Updating UI outside main thread
  • Ignoring optional unwrapping safety

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes