Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Apple's reachability class in Swift

Tags:

ios

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
like image 775
Sam Avatar asked Sep 19 '14 07:09

Sam


People also ask

What is reachability in IOS Swift?

Network Reachability is the network state of the user's device. We can use it to understand if the device is offline or online using either wifi or mobile data.

What is Reachability in iOS?

When you use iPhone with one hand in Portrait orientation, you can use Reachability to lower the top half of the screen so it's within easy reach of your thumb. Go to Settings > Accessibility > Touch, then turn on Reachability.

How do I check network reachability?

Answer. Ping is a network utility that is used to test if a host is reachable over a network or over the Internet by using the Internet Control Message Protocol “ICMP”. When you initiate an ICMP request will be sent from a source to a destination host.

How do I check my Internet connection in Swift?

In the viewWillAppear method, add an observer to the Notification Center, so every time the network state changes, like from Wifi goes to Cellular, this will be detected instantly and call the reachabilityChanged method. And in the viewDidDisappear method, remove the stop the notifier and remove the observer.


1 Answers

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)
like image 102
Ramesh Avatar answered Sep 30 '22 02:09

Ramesh