2

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?

Marty
  • 5,926
  • 9
  • 53
  • 91
  • Well, you're force unwrapping your url, though unlikely to cause the problem. Are you actually hitting the `.success` case? Also, is `image` a type of `View` – xTwisteDx Feb 04 '22 at 02:14

1 Answers1

3

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
                }
            }
        }
    }
}
dudette
  • 788
  • 3
  • 8
  • That does work, but I don't understand why...random magical fix or is there a reason? – Marty Feb 04 '22 at 02:31
  • as far as I know, `EmptyView` represents the absence of a view, but the `AsyncImage` expect to show some sort of view. But then again, it's all magic to me. You could also replace the `Color.clear` with the more appropriate `ProgressView()` – dudette Feb 04 '22 at 02:40
  • But `EmptyView` conforms to `View`, so...not sure why it would cancel the load :shrug: – Marty Feb 04 '22 at 02:58
  • Interesting issue! Even if you would only use `AsyncImage(url: URL(string: "https://i.scdn.co/image/ab6761610000e5ebb78f77c5583ae99472dd4a49"))` without callback, the image wouldn't load on iOS 15. On iOS 16, it seems to be resolved. – MrJre Aug 22 '23 at 08:23