AlamofireImage - fetching image using MVVM

78 Views Asked by At

We are using AlamofireImage in our project to make use of its image caching system. However, I'm wondering the best way to fetch the image without contradicting MVVM.

Alamofire's image download method returns the following type: AFIDataResponse<Image>.

Therefore the obvious way to implement is via the following:

func fetchImage() {
        guard let imageURL = viewModel.imageURL else { return }
        let urlRequest = URLRequest(url: imageURL)

        imageDownloader.download(urlRequest, completion: { response in
            if case .success(let image) = response.result {
                self.productImage = image
            }
        })
    }

However, this means including this logic within the view itself, which is not ideal. Particularly given that I would like to also add an isLoading publisher to present a loading view when the image is downloading.

However, if I move this logic into the viewModel, we then have to declare productImage in said viewModel and import UIKit, which again is not ideal. Both work, but neither seems to stick correctly to MVVM.

0

There are 0 best solutions below