I'm observing a bizarre thing: in the new widgets far too often remote images are not being displayed even though the image has been successfully loaded and placed in cache.
For image downloading I've tried:
All of them indicate that image loading succeed, but the actual widget is not showing it.
struct TestWidgetEntryView : View {
var entry: Provider.Entry
var body: some View {
WebImage(url: URL(string: "https://miro.medium.com/max/3840/0*TLqp5Uwavd-U_xrs.jpg"))
.onSuccess()
.resizable()
}
}
On the second run of the debugger - with image loading from cache - I get the image displayed, but never(?) on initial run.
It feels like that in onSuccess I need to trigger UI-invalidation? But how?
(Since it happens to literally every image-lib I try - I don't think that it's something off in the libs)
Environment:
Yes, as mentioned by Konstantin, it is not supported to load images asynchronously. There are 2 options to load network image in widgets
Either fetch all the images in TimelineProvider and inject them to the views directly.
OR
Use Data(contentsOf: url)
to fetch the image. This way it still fetches them synchronously but the code is cleaner. Sample code -
struct NetworkImage: View {
let url: URL?
var body: some View {
Group {
if let url = url, let imageData = try? Data(contentsOf: url),
let uiImage = UIImage(data: imageData) {
Image(uiImage: uiImage)
.resizable()
.aspectRatio(contentMode: .fill)
}
else {
Image("placeholder-image")
}
}
}
}
This view can simply be use like this -
NetworkImage(url: url)