0

I've made connection checker according to this question How to check internet connection in alamofire?

import Foundation
import Alamofire
class Connectivity {
class var isConnectedToInternet:Bool {
    return NetworkReachabilityManager()?.isReachable ?? false
    }
}

And I'm checking connection before I make request like this

    func fetchPhotos() {
    if Connectivity.isConnectedToInternet{
        newOrPopularChooser(self.page)
            .observe(on: MainScheduler.instance)
            .subscribe{ (response) in
                self.photos.append(contentsOf: response.data)
                self.page += 1
                if self.page == response.countOfPages {
                    self.isEndReached = true
                }
                self.view?.onFetchPhotoSuccess()
            } onError: { error in
                self.view?.onFetchPhotoFailure(error: error.localizedDescription)
            }.disposed(by: disposeBag)
    } else {
        self.view?.onFetchPhotoFailure(error: "No Internet connection")
    }
}

And here is the code of fetch photo success and failure

func onFetchPhotoSuccess() {
    self.refreshControl.endRefreshing()
    footerView.stopAnimating()
    self.isLoadingList = false
    self.collectionView.reloadData()
    if !(self.presenter?.photos.isEmpty)! {
    self.collectionView!.collectionViewLayout.invalidateLayout()
    self.collectionView!.layoutSubviews()
    self.collectionView.backgroundView = nil
    }
}

func onFetchPhotoFailure(error: String) {
    print("View receives the response from Presenter with error: \(error)")
    let storyboard = UIStoryboard(name: "NoInternetConnectionView", bundle: .main)
    let controller = storyboard.instantiateViewController(identifier: "NoInternetConnectionVC")
    self.presenter?.photos = []
    self.collectionView.reloadData()
    collectionView.backgroundView = controller.view
    self.refreshControl.endRefreshing()
    footerView.stopAnimating()
}

So if I have internet on I see my collection but when I'm turning my internet off and then turning it back and reload my collection view I'm getting empty collectionView. No no internet connection background just empty background like thisenter image description here

Ivanius
  • 109
  • 1
  • 2
  • 9

1 Answers1

1

Do not do this. Apple has long told us that checking for connectivity before issuing a network request is an anti pattern. This is for many reasons, but the biggest is the fact that the reachability check may be inaccurate or take inordinate time to produce an answer. It's far better to make the network request and handle any failure that may occur.

Jon Shier
  • 12,200
  • 3
  • 35
  • 37