Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect change in internet connection on iOS, delegate style?

I need a function to run only when the system detects there is no internet connection, then another function to run when the system detects an internet connection.

I'm thinking of something like this:

func onInternetConnection() {
    //Enable actions
}

func onInternetDisconnection() {
    //Disable actions, alert user
}

I will also need a way to detect when the system is reconnecting, so I can let the user know it's reconnecting, like in Facebook's Messenger.

How can I do this?

I'm using Moya/Alamofire for my network layer.

like image 756
Berry Avatar asked May 09 '17 09:05

Berry


1 Answers

This works in case of Alamofire

import Alamofire

// In your view did load or in app delegate do like this
let reachabilityManager = NetworkReachabilityManager()
reachabilityManager.listener = { status in

  switch status {

  case .notReachable:
    print("The network is not reachable")
    self.onInternetDisconnection()

  case .unknown :
    print("It is unknown whether the network is reachable")
    self.onInternetDisconnection() // not sure what to do for this case

  case .reachable(.ethernetOrWiFi):
    print("The network is reachable over the WiFi connection")
    self.onInternetConnection()

  case .reachable(.wwan):
    print("The network is reachable over the WWAN connection")
    self.onInternetConnection()

  }
}
like image 77
Inder Kumar Rathore Avatar answered Nov 10 '22 16:11

Inder Kumar Rathore