Skip to content

Instantly share code, notes, and snippets.

@ricardopereira
Forked from chriseidhof/asyncimages.swift
Created June 8, 2019 09:24
Show Gist options
  • Save ricardopereira/1e2bda707d7cd2b05fa72cea7570e35e to your computer and use it in GitHub Desktop.
Save ricardopereira/1e2bda707d7cd2b05fa72cea7570e35e to your computer and use it in GitHub Desktop.
final class Loader: BindableObject {
let didChange = PassthroughSubject<Data?, Never>()
var task: URLSessionDataTask!
var data: Data? = nil {
didSet {
didChange.send(data)
}
}
init(_ url: URL) {
task = URLSession.shared.dataTask(with: url, completionHandler: { data, _, _ in
DispatchQueue.main.async {
self.data = data
}
})
task.resume()
}
deinit {
task.cancel()
}
}
let placeholder = UIImage(named: "placeholder.jpg")!
struct MyView: View {
init(url: URL) {
self.imageLoader = Loader(url)
}
@ObjectBinding private var imageLoader: Loader
var image: UIImage? {
imageLoader.data.flatMap(UIImage.init)
}
var body: some View {
Image(uiImage: image ?? placeholder)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment