How to properly execute tasks in a background thread in Swift (Grand Central Dispatch)
Hello everyone! I'm new to Swift and iOS development. I'm writing a simple app for downloading images from the internet. When I click the "Download" button, the interface freezes for a few seconds until the image appears. I've heard that I need to use background threads to avoid blocking the main thread (UI). But I don't understand how to do this correctly in Swift.
Here's my current code:
```swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBAction func loadImageTapped(_ sender: UIButton) {
// Problem: this code runs on the main thread
let url = URL(string: "https://example.com/large-image.jpg")!
let data = try! Data(contentsOf: url)
imageView.image = UIImage(data: data)
}
}
```