Avatar ·

Loading and displaying an image from URL in Swift (UIImage)

Hello! I just started learning Swift and am trying to make a simple app that shows an image from the internet. I have a URL string with an image, for example: `"https://example.com/image.jpg"`. I'm trying to load this image and display it in a `UIImageView`. Here's my code: ```swift let url = URL(string: "https://example.com/image.jpg") let data = try? Data(contentsOf: url!) imageView.image = UIImage(data: data!) ``` But it doesn't work — the app freezes for a few seconds and then crashes with an error. I read that `Data(contentsOf:)` can block the main thread, but how do I properly load the image? I've heard about `URLSession`, but I don't understand how to use it. Please tell me how to correctly and safely load an image from the network in Swift? I need