Skip to content

Instantly share code, notes, and snippets.

@SwiftyAlex
Last active March 14, 2020 14:44
Show Gist options
  • Save SwiftyAlex/458232ab7e105a4dc087fbf5c5784c19 to your computer and use it in GitHub Desktop.
Save SwiftyAlex/458232ab7e105a4dc087fbf5c5784c19 to your computer and use it in GitHub Desktop.
import Combine
import UIKit
@propertyWrapper
class ImageDownloading {
var wrappedValue: UIImageView
private var cancellable: AnyCancellable?
init(wrappedValue: UIImageView, url: URL?, urlSession: URLSession) {
self.wrappedValue = wrappedValue
wrappedValue.image = UIImage(named: "placeholder")
guard let url = url else { return }
performFetch(from: url, using: urlSession)
}
func performFetch(from url: URL, using urlSession: URLSession) {
cancellable = urlSession.dataTaskPublisher(for: url)
.subscribe(on: DispatchQueue.global(qos: .background)) // Force the background thread
.map(\.data)
.map{ UIImage(data: $0) }
.replaceError(with: UIImage(named: "placeholder"))
.receive(on: RunLoop.main) // Hop back on the main thread
.assign(to: \.image, on: wrappedValue)
}
}
// Usage
@ImageDownloading(url: URL(string: "http://alexanderlogan.co.uk/images/snippit.png"), urlSession: .shared)
var headerImageView: UIImageView = UIImageView()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment