Swift Real-time monitoring of network status

created at 11-15-2021 views: 1

1) With the help of Alamofire

  • real-time
  • Can be used globally
  • Protocol-oriented programming ideas

2) How to use

For common scenarios such as UIViewController, follow the CCNetworkStatusProtocol protocol.
Similarly, in `class` such as UIView, AppDelegate, etc., follow the CCNetworkStatusProtocol protocol.
Through the return value of the isReachable method, you can verify the judgment.

class CCViewController: UIViewController, CCNetworkStatusProtocol {
     if isReachable() {
       print("Network available")
     } else {
       print("Network unavailable")
     }
  }

3) Source code sharing

/// Network status protocol
protocol CCNetworkStatusProtocol {
     func isReachable() -> Bool
}

extension CCNetworkStatusProtocol {
     /// Return a boolean value for real-time monitoring of the network status
     func isReachable() -> Bool {
         var res: Bool = false
         let netManager = NetworkReachabilityManager()
         if netManager?.status == .reachable(.ethernetOrWiFi) || netManager?.status == .reachable(.cellular) {res = true}
         return res
     }
}
created at:11-15-2021
edited at: 11-15-2021: