Loading image from remote URL asynchronously in SwiftUI Image using combine's Publisher

人走茶凉 提交于 2021-01-28 20:03:05

问题


I was looking for good solutions for loading images asynchronously from a remote server image URL. There were many solutions online. It's a shame Apple doesn't provide one natively for something that is so common. Anyways, I found Sundell's blog really interesting and took the good bits from it to create my own ImageLoader, as shown below:

import Combine

class ImageLoader {

    private let urlSession: URLSession
    private let cache: NSCache<NSURL, UIImage>

    init(urlSession: URLSession = .shared,
         cache: NSCache<NSURL, UIImage> = .init()) {
        self.urlSession = urlSession
        self.cache = cache
    }

    func publisher(for url: URL) -> AnyPublisher<UIImage, Error> {
        if let image = cache.object(forKey: url as NSURL) {
            return Just(image)
                .setFailureType(to: Error.self)
                .receive(on: DispatchQueue.main)
                .eraseToAnyPublisher()
        } else {
            return urlSession
                .dataTaskPublisher(for: url)
                .map(\.data)
                .tryMap { data in
                    guard let image = UIImage(data: data) else {
                        throw URLError(.badServerResponse, userInfo: [
                            NSURLErrorFailingURLErrorKey: url
                        ])
                    }
                    return image
                }
                .receive(on: DispatchQueue.main)
                .handleEvents(receiveOutput: { [cache] image in
                    cache.setObject(image, forKey: url as NSURL)
                })
                .eraseToAnyPublisher()
        }
    }
}

As you can see the publisher provides an instance of AnyPublisher<UIImage, Error>. I'm not entirely sure on how to use this ImageLoader in my MyImageView shown below:

struct MyImageView: View {

    var url: URL
    var imageLoader = ImageLoader()

    @State private var image = #imageLiteral(resourceName: "placeholder")

    var body: some View {
        Image(uiImage: image)
            .onAppear {
                let cancellable = imageLoader.publisher(for: url).sink(receiveCompletion: { failure in
                    print(failure) // doesn't print
                }, receiveValue: { image in
                    self.image = image // not getting executed
                })
                cancellable.cancel() // tried with and without this line.
            }
    }
}

How do I extract the UIImage from the ImageLoader publisher that returns an instance of AnyPublisher<UIImage, Error>?


回答1:


You have to use an ObservableObject for subscribing to the publisher provided by ImageLoader.

class ImageProvider: ObservableObject {
    @Published var image = UIImage(named: "icHamburger")!
    private var cancellable: AnyCancellable?
    private let imageLoader = ImageLoader()

    func loadImage(url: URL) {
        self.cancellable = imageLoader.publisher(for: url)
            .sink(receiveCompletion: { failure in
            print(failure)
        }, receiveValue: { image in
            self.image = image
        })
    }
}

struct MyImageView: View {
    var url: URL
    @StateObject var viewModel = ImageProvider()
    var body: some View {
        Image(uiImage: viewModel.image)
            .onAppear {
                viewModel.loadImage(url: url)
            }
    }
}



回答2:


Since I didn't want too much segregation for a simple ImageLoader, I made it conform to ObservableObject. So, I'm just modifying the answer provided by @sElanthiraiyan. Also, with a bit more research I found that the publisher needs to be stored when required and deallocated when it's no longer used. Here's the modified code

ImageLoader:

class ImageLoader: ObservableObject {

    @Published var image: UIImage
    private var bag = Set<AnyCancellable>()
    //...

    init(placeholder: UIImage = UIImage(),
         urlSession: URLSession = .shared,
         cache: NSCache<NSURL, UIImage> = .init()) {
        self.image = placeholder
        //...
    }

    //...

    func load(from url: URL) {
        publisher(for: url)
            .sink(receiveCompletion: { _ in })
            { image in
                self.image = image
            }
            .store(in: &bag)
    }
}

MyImageView:

struct MyImageView: View {

    var url: URL
    @StateObject var imageLoader = ImageLoader(placeholder: UIImage(named: "placeholder")!) // or @ObservedObject if iOS 13 support is required

    var body: some View {
        Image(uiImage: imageLoader.image)
            .onAppear {
                imageLoader.load(from: url)
            }
    }
}


来源:https://stackoverflow.com/questions/64854765/loading-image-from-remote-url-asynchronously-in-swiftui-image-using-combines-pu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!