Using Apple's reachability class in Swift

前端 未结 4 951
余生分开走
余生分开走 2020-12-08 16:33

I am rewriting my existing Objective-C code (iOS) to Swift and now am facing some issues with the Reachability class of Apple for checking network availability.

相关标签:
4条回答
  • 2020-12-08 16:59

    put this code in to your appDelegate for checking reachability .

    //MARK: reachability class
    func checkNetworkStatus() -> Bool {
        let reachability: Reachability = Reachability.reachabilityForInternetConnection()
        let networkStatus = reachability.currentReachabilityStatus().rawValue;
        var isAvailable  = false;
    
        switch networkStatus {
        case (NotReachable.rawValue):
            isAvailable = false;
            break;
        case (ReachableViaWiFi.rawValue):
            isAvailable = true;
            break;
        case (ReachableViaWWAN.rawValue):
            isAvailable = true;
            break;
        default:
            isAvailable = false;
            break;
        }
        return isAvailable;
    }
    
    0 讨论(0)
  • 2020-12-08 17:08

    Simply use like this

    do {
        let reachability: Reachability = try Reachability.reachabilityForInternetConnection()
    
         switch reachability.currentReachabilityStatus{
         case .ReachableViaWiFi:
             print("Connected With wifi")
         case .ReachableViaWWAN:
             print("Connected With Cellular network(3G/4G)")
         case .NotReachable:
             print("Not Connected")
         }
    }
    catch let error as NSError{
        print(error.debugDescription)
    }
    
    0 讨论(0)
  • 2020-12-08 17:10

    Try below code

     let connected: Bool = Reachability.reachabilityForInternetConnection().isReachable()
    
            if connected == true {
                 println("Internet connection OK")
            }
            else
            {
                println("Internet connection FAILED")
                var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
                alert.show()
            }
    
    0 讨论(0)
  • 2020-12-08 17:19

    For network availability (works in Swift 2):

    class func hasConnectivity() -> Bool {
        let reachability: Reachability = Reachability.reachabilityForInternetConnection()
        let networkStatus: Int = reachability.currentReachabilityStatus().rawValue
        return networkStatus != 0
    }
    

    For a Wi-Fi connection:

    (reachability.currentReachabilityStatus().value == ReachableViaWiFi.value)
    
    0 讨论(0)
提交回复
热议问题