Loading Remote Images in SwiftUI

In UIKit we've often lamented the fact that there is no builtin facility to load an image with a URL, leaving developers to implement this on their own. In SwiftUI the situation is the same, however we have more flexibility to build what we need. Using a Swift package called FetchImage, we will create a reusable ImageView struct that can load our images efficiently given a URL.

This is a companion discussion topic for the original entry at https://nsscreencast.com/episodes/434-swiftui-loading-remote-images

Hey @benscheirman

FetchImage is now archived, but you could still use it: just have to type https://github.com/kean/FetchImage.git instead just FetchImage in the swift packages search bar to find it, also version of 0.1.0 used in the video works with Swift 5 / Xcode 13.4.1.

If I understand the lib author’s intention, FetchImage is sort of moved to NukeUI, which could be added as an SPM package via https://github.com/kean/NukeUI. They also seem to handle start loading when on screen and cancel loading when off-screen. Here’s what my ImageView looks like with NukeUI

struct ImageView: View {
    let url: URL
    @State private var isLoaded = false
    
    var body: some View {
        ZStack {
            LazyImage(source: url, resizingMode: .aspectFit)
                .onCompletion { result in
                    isLoaded = true
                }
            
            if !isLoaded {
                Rectangle()
                    .fill(Color.gray)
            }
        }
        .frame(width: 120, height: 160)
    }
}

Seems cool. But I still would you use NukeUI now or something else?

Thanks