简体   繁体   中英

How to get UIImage from AnyPublisher<UIImage?, Never> Swift 5 (Combine framework)

Im trying to figure how to use Reusable Image Cache in Swift with a UIImageView. I am trying to simply assign the ImageLoader() variable's, actual image to a UIImageView so I can use it as a UIImage.

Code:

let loader = ImageLoader()

myImage.image = loader.loadImage(from: myUrl)

maybe:

loader.loadImage(from: myUrl)

myImage.image = loader(image)

But this give a cannot call value of non-function type 'ImageLoader' error

Code:

final class ImageLoader {

private let cache = ImageCache()

func loadImage(from url: URL) -> AnyPublisher<UIImage?, Never> {
    if let image = cache[url] {
        return Just(image).eraseToAnyPublisher()
    }
    return URLSession.shared.dataTaskPublisher(for: url)
        .map { UIImage(data: $0.data) }
        .catch { error in return Just(nil) }
        .handleEvents(receiveOutput: {[unowned self] image in
            guard let image = image else { return }
            self.cache[url] = image
        })
        .subscribe(on: DispatchQueue.global(qos: .background))
        .receive(on: RunLoop.main)
        .eraseToAnyPublisher()
}
}

You are trying to set the publisher result to the ImageView. You need to use something like this:

 class SomeTestClass {

    let imageView = UIImageView()
    var subscriptions = Set<AnyCancellable>()

    func loadImage() {

        ImageLoader().loadImage(from: URL(string: "someURL")!).sink { (image) in
            self.imageView.image = image
        }.store(in: &subscriptions)

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM