Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

ios - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...