Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct Banner: Decodable {
- let bannerImageUrl: String
- // coding keys
- }
- protocol ImageBannerService {
- func load(completion: @escaping (([Banner]?, Error?) -> Void))
- func load(_ image: URL, completion: @escaping ((UIImageView?, Error?) -> Void))
- }
- class ImageBannerServiceImpl {
- func load(completion: @escaping (([Banner]?, Error?) -> Void)) {
- DispatchQueue.global(qos: .background).async {
- let banners: [Banner] = []
- completion(banners, nil)
- }
- }
- func load(_ image: URL, completion: @escaping ((UIImageView?, Error?) -> Void)) {
- DispatchQueue.global(qos: .background).async {
- // .. код загрузки изображения из сети
- let data = Data(contentsOf: image)
- let loadedImage = UIImage(data: data)
- let imageView = UIImageView(image: loadedImage)
- completion(imageView, nil)
- }
- }
- }
- class BannerCollectionViewController: UIViewController, UICollectionViewDataSource {
- let service: ImageBannerService = ImageBannerServiceImpl()
- lazy var collectionView: UICollectionView = {
- let collectionView = UICollectionView()
- collectionView.dataSource = self
- return collectionView
- }()
- var banners = [Banner]()
- override func viewDidLoad() {
- view.backgroundColor = .white
- view.addSubview(collectionView)
- NSLayoutConstraint.activate([
- ])
- service.load { [weak self] banners, error in
- DispatchQueue.main.async {
- self?.banners = banners!
- self?.collectionView.reloadData()
- }
- }
- }
- func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
- return banners.count
- }
- func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
- guard let cell = collectionView.dequeueReusable(for: id, indexPath: indexPath) as? BannerCell else { return UICollectionViewCell() }
- let banner = banners[indexPath.row]
- let imageUrlString = banner.banner_image_url
- guard let image = banners[indexPath.row].banner_image_url else { return cell }
- cell.currentUrlString = imageUrlString
- service.load(image) { imageView, error in
- if imageUrlString == cell.currentUrlString,
- let imageView {
- DispatchQueue.main.async {
- cell.imageView = imageView
- }
- }
- }
- return cell
- }
- }
- class BannerCell: UICollectionViewCell {
- var imageView: UIImageView
- var currentUrlString: String?
- override func prepareForReuse() {
- closure = nil
- currentUrlString = nil
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement