0

My current code for fetching image from String with SwiftUI is:

import SwiftUI
struct NetworkImage: View {
    let url: URL?
    var body: some View {
        if let url = url, let imageData = try? Data(contentsOf: url), let uiImage = UIImage(data: imageData) {
            Image(uiImage: uiImage)
        }
    }
}

It is fine when I use it using WidgetKit on iOS. But it doesn't work when I am trying to use the same on watchOS.

Error on console:

Synchronous URL loading of https://www.imageurl.here should not occur on this application's main thread as it may lead to UI unresponsiveness. Please switch to an asynchronous networking API such as URLSession.

That question does not answer my question as of it is not with UIKit, but with SwiftUI on watchOS.

jnpdx
  • 45,847
  • 6
  • 64
  • 94
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358

1 Answers1

0

Since iOS 15 and watchOS 8.0 it can be done using:

AsyncImage(url: url)

If there is a need to access an image and modify it directly use closure:

AsyncImage(url: url) { phase in
    phase.image?
        .resizable() // example
        .scaledToFill() // example
}
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358