Check Internet connection availability?

前端 未结 4 1946
悲哀的现实
悲哀的现实 2021-01-17 19:20

I just need to check the internet connection availability before start communicating with the service in my iphone App. I am using Swift 1.2 and Xcode 6 as my development en

4条回答
  •  萌比男神i
    2021-01-17 19:42

    Alamofire

    I would recommend listen to reachability instead of using a get api.

    You can add following class to your app, and call MNNetworkUtils.main.isConnected() to get a boolean on whether its connected or not.

    class MNNetworkUtils {
      static let main = MNNetworkUtils()
      init() {
        manager = NetworkReachabilityManager(host: "google.com")
        listenForReachability()
      }
    
      private let manager: NetworkReachabilityManager?
      private var reachable: Bool = false
      private func listenForReachability() {
        self.manager?.listener = { [unowned self] status in
          switch status {
          case .notReachable:
            self.reachable = false
          case .reachable(_), .unknown:
            self.reachable = true
          }
        }
        self.manager?.startListening()
      }
    
      func isConnected() -> Bool {
        return reachable
      }
    }
    

    This is a singleton class. Every time, when user connect or disconnect the network, it will override self.reachable to true/false correctly, because we start listening for the NetworkReachabilityManager on singleton initialization.

    Also in order to monitor reachability, you need to provide a host, currently I am using google.com feel free to change to any other hosts or one of yours if needed.

提交回复
热议问题