Skip to content

Instantly share code, notes, and snippets.

@wtsnz
Created October 12, 2019 18:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wtsnz/e09be7926115a8ac883c7c72ea5789dc to your computer and use it in GitHub Desktop.
Save wtsnz/e09be7926115a8ac883c7c72ea5789dc to your computer and use it in GitHub Desktop.
(Extremely) Basic way to load a remote image from URL in SwiftUI
import Combine
import SwiftUI
class RemoteImageLoader: ObservableObject {
@Published var data: Data = Data()
init(imageURL: URL) {
URLSession.shared.dataTask(with: imageURL) { data, response, error in
guard let data = data else { return }
DispatchQueue.main.async { self.data = data }
}
.resume()
}
}
struct URLImage: View {
@ObservedObject var remoteImageLoader: RemoteImageLoader
init(_ imageUrl: URL) {
remoteImageLoader = RemoteImageLoader(imageURL: imageUrl)
}
var body: some View {
Image(uiImage: UIImage(data: remoteImageLoader.data) ?? UIImage())
.resizable()
.renderingMode(.original)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment