Last active
September 15, 2022 19:02
-
-
Save chriseidhof/2c3bcdfa5bfa0795b33bd17f1e88771d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Thanks, dear....really you save my day.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks man this was really useful :)