Last active
March 14, 2020 14:44
-
-
Save SwiftyAlex/458232ab7e105a4dc087fbf5c5784c19 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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