sam sam - 6 months ago 31
Swift Question

Using Apple's reachability class in Swift

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... In my existing code I am using the following for achieving that.

var reachability: Reachability = Reachability.reachabilityForInternetConnection()
var internetStatus:NetworkStatus = reachability.currentReachabilityStatus()
if (internetStatus != NotReachable) {
//my web-dependent code
}
else {
//There-is-no-connection warning
}


And I am getting this error:
network status is not convertible to string
at this line:

if (internetStatus != NotReachable)


Is there a method or class for getting network status?

I need these three conditions:

NotReachable: Obviously, there’s no Internet connection
ReachableViaWiFi: Wi-Fi connection
ReachableViaWWAN: 3G or 4G connection

Answer

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