6

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.

Berry
  • 2,143
  • 4
  • 23
  • 46
  • Alamofire have network reachability included, read about it [here](https://github.com/Alamofire/Alamofire#network-reachability), it use block, kinda better than delegate – Tj3n May 09 '17 at 09:39
  • Take a look at the answer [here](http://stackoverflow.com/questions/25398664/check-for-internet-connection-availability-in-swift) – Devika S May 09 '17 at 09:42
  • Check [this lib](https://github.com/ashleymills/Reachability.swift#example---closures) too, it can trigger closures when the status of your internet connection changes. – Toldy May 09 '17 at 09:50

2 Answers2

4

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()

  }
}
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
0

Alamofire and Rechability are library and that have some features to check internet connection. You can use one from that.

Rohan Dave
  • 251
  • 1
  • 7