Loading image from URL in Swift: how to do it correctly and asynchronously?
Hello everyone! I'm a beginner in Swift and iOS development. I'm writing an app that displays a list of products with images. The images are loaded from the internet via URL. I wrote a simple function, but it works very strangely: the interface freezes for a few seconds, and sometimes images don't display at all. Here's my code:\n\n```swift\nfunc loadImage(from urlString: String) -> UIImage? {\n guard let url = URL(string: urlString) else { return nil }\n if let data = try? Data(contentsOf: url) {\n return UIImage(data: data)\n }\n return nil\n}\n```\n\nI call this function directly in `cellForRowAt` for each table cell. Apparently, this is bad practice? Also, I noticed that when scrolling quickly, the images start to "jump" — showing the wrong pictures. Please advise how to do it correctly.
No answers yet.
Log in to leave an answer