iosswiftuiswiftui-asyncimage

AsyncImage not loading inside VStack


When using an AsyncImage inside a VStack, the image never loads. The handler is called once, and the AsyncImagePhase is .empty. Sample code:

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            AsyncImage(url: URL(string: "https://i.scdn.co/image/ab6761610000e5ebb78f77c5583ae99472dd4a49")!) { phase in
                switch phase {
                case .success(let image):
                    image
                default: EmptyView()
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

If you remove the VStack, the image loads (only when you run the app though; the Simulator in the Canvas window disappears in this case.)

I assume this is a SwiftUI bug. Any known workarounds?


Solution

  • try this, replacing EmptyView() : (note there is no need for the "!" for the url)

    struct ContentView: View {
        var body: some View {
            VStack {
                AsyncImage(url: URL(string: "https://i.scdn.co/image/ab6761610000e5ebb78f77c5583ae99472dd4a49")) { phase in
                    switch phase {
                    case .success(let image):
                        image
                    default: Color.clear // <-- here
                    }
                }
            }
        }
    }