To download an image using Combine, you need to use URLSession to make a network request and then decode the response into an image. Here's an example of how you can do it:
main.swift486 chars17 lines
In this example, downloadImage(from:)
takes a URL and returns a publisher that emits a UIImage
or nil
, and never fails. It uses dataTaskPublisher(for:)
to create a publisher that emits a (data: Data, response: URLResponse)
tuple when a network request completes. Then, it maps the data to a UIImage
, replaces any errors with nil
, and erases the types to create a publisher that emits a UIImage?
.
To use downloadImage(from:)
, you call it with a URL, which returns a publisher that you can subscribe to, typically using sink(receiveValue:)
. In the closure, you can do something with the downloaded image, like displaying it in an image view.
gistlibby LogSnag