URLImage Never Loads Image in Widget App for SwiftUI

2.1k Views Asked by At

Simple code for an iOS Widget, I have verified the meme is loaded with the meme.url value from an earlier HTTP request. I've also checked printing the url text on it's own and that works too, but I can't load the image with the URLImage package. I've tried on the widget and the contentview as well and no results. Any ideas?

meme.url is a URL type which is an optional.

URLImage: https://github.com/dmytro-anokhin/url-image

NOTE: To be more specific, the placeholder does appear, not the image from the url though. Here is an example url: https://i.redd.it/zey35zvw4gq51.jpg

import SwiftUI
import URLImage

struct MemeView: View {
    let meme: MemeModel

    var body: some View {
        URLImage(meme.url!, placeholder: Image(systemName: "square"))
    }
}
1

There are 1 best solutions below

2
On

Figured it out. No Need for URLImage. Problem is widgets cannot handle asynchronous calls so you have to wrap it like so:

struct MemeView: View {
var meme: MemeModel

var body: some View {
    Group {
        if let url = meme.url!, let imageData = try? Data(contentsOf: url),
       let uiImage = UIImage(data: imageData) {

       Image(uiImage: uiImage)
         .resizable()
         .aspectRatio(contentMode: .fill)
      }
      else {
       Image("placeholder-image")
      }
    }

}