Reachability issue while refreshing

426 Views Asked by At

First my code

 func checkInternetConnection() {

    reachability.whenReachable = { _ in
            self.loadPost()
            self.checkNewMessages()
            self.slowView.frame.size.height = 0
            self.slowView.isHidden = true
            self.internetStatus.text = ""
            self.slowView.layer.zPosition = 0
    }
    reachability.whenUnreachable = { _ in
        self.refreshControl.endRefreshing()
        self.slowView.backgroundColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1)
        self.slowView.layer.zPosition = 1
        self.slowView.frame.size.height = 40
        self.slowView.isHidden = false
        self.internetStatus.text = "Keine Internetverbindung!"
        self.activityIndicatorView.stopAnimating()
        self.Indicator.stopAnimating()

    }
    NotificationCenter.default.addObserver(self, selector: #selector(self.internetChanged(note:)), name: Notification.Name.reachabilityChanged, object: self.reachability)
    do {
        try self.reachability.startNotifier()
    }catch {
        print("error")
    }

}

@objc func internetChanged(note: Notification) {
    let reachability = note.object as! Reachability
    if reachability.connection != .none {
            self.slowView.backgroundColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
            self.slowView.layer.zPosition = 1
            self.slowView.frame.size.height = 40
            self.slowView.isHidden = false
            self.internetStatus.text = "Mit dem Internet verbunden!"
            DispatchQueue.main.asyncAfter(deadline: .now() + 3 , execute: {
                self.slowView.layer.zPosition = 0
                self.slowView.frame.size.height = 0
            })

    } else {
        print("kein internet")
    }

}

I call the checkInternetConnection() method in viewDidLoad() and its works fine but as soon as I refresh my tableview it does not enter the reachability closure.

In handleRefresh() ( works fine for just reloading the posts) the checkInternetConnection() method is called but does not fire any code, the issue only appears while refreshing, not the initial loading.

I used this video for reference: https://www.youtube.com/watch?v=wDZmz9IsB-8 Any advice?

1

There are 1 best solutions below

2
dr_barto On

I think (but am not 100% sure) that the closures whenReachable and whenUnreachable are only called when the appropriate reachability change happens; in addition they might get called automatically when they are assigned. So no matter how often you call your checkInternetConnection the closures won't get re-executed unless the device goes offline/online.

To fix this I suggest to instead use the reachability flags:

if reachability.isReachable {
  // update view for reachable state
}
else {
  // update view for unreachable state
}