I’m making an attempt to load the picture from url and present it into assortment view cell. I’m following MVVM . Right here is the URL return single picture https://picsum.photographs/200 . I’ve set the cell with delegate and knowledge supply , I’m not capable of finding out why the picture will not be reddening into assortment view.
Right here is the code for community layer..
import Basis
import UIKit
enum ImageFetchingError: Error {
case timeout
case unknown
}
protocol CatImageCellModel {
func fetchCatImage(completion: @escaping (Consequence) -> Void)
}
class NetworkLayer: CatImageCellModel {
func fetchCatImage(completion: @escaping (Consequence) -> Void) {
let url = "https://picsum.photographs/200"
guard let _url = URL(string: url) else {
return
}
URLSession.shared.dataTask(with: _url) { knowledge, response, error in
guard
let knowledge = knowledge,
let picture = UIImage(knowledge: knowledge),
let response = response as? HTTPURLResponse,
response.statusCode >= 200 && response.statusCode < 300 else {
completion(.failure(.unknown))
return
}
completion(.success(picture))
}.resume()
}
}
Right here is the code for view mannequin..
import Basis
import UIKit
class ViewModel {
non-public let networkLayer: NetworkLayer
public var picture: UIImage = UIImage()
init(networkLayer: NetworkLayer = NetworkLayer()) {
self.networkLayer = networkLayer
}
func fatchImage() {
networkLayer.fetchCatImage { [weak self] end in
change consequence {
case .success(let picture):
self?.picture = picture
print(picture)
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
Right here is the code for view..
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
non-public var viewModel = ViewModel()
override func viewDidLoad() {
viewModel.fatchImage()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection part: Int) -> Int {
1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! CollectionViewCell
// return card
let picture = viewModel.picture
cell.imageView.picture = picture
return cell
}
}
Right here is the cell code ..
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
override func prepareForReuse() {
imageView = nil
imageView?.alpha = 0.5
}
}
Right here is the consequence after I run the app which is clean..
screenshot…
(https://i.sstatic.web/v8nKFZIo.png)