Using Apple's Reachability to check remote server reachability in Swift

pseudorandomuser picture pseudorandomuser · Jul 12, 2014 · Viewed 19.2k times · Source

I'm developing an iOS application written in Swift that communicates with a HTTP server on the local network, and I'm using Apple's Reachability class to determine wether the remote machine running the HTTP server is online or not. Here's the code:

...
let RemoteHost: String = "192.168.178.130"
var RemoteReachability: Reachability! = nil
var RemoteIsReachable: Bool = false

init() {
        super.init()
        self.RemoteReachability = Reachability(hostName: self.RemoteHost)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: kReachabilityChangedNotification, object: self.RemoteReachability)
        self.RemoteReachability.startNotifier()
        self.RemoteIsReachable = (self.RemoteReachability.currentReachabilityStatus().value == ReachableViaWiFi.value)
}

func reachabilityChanged(notification: NSNotification) {
    let ReachabilityInst: Reachability = notification.object as Reachability
    self.RemoteIsReachable = (ReachabilityInst.currentReachabilityStatus().value == ReachableViaWiFi.value)
}

The problem is that no matter if the remote machine is online or offline,

(ReachabilityInst.currentReachabilityStatus().value == ReachableViaWiFi.value)

Is always true, as long as I'm connected to a Wifi network. However, when I turn Wifi off, it results in being false instead of true. Am I doing something wrong here, or is the Reachability class just not compatible with Swift/xCode 6 Beta yet? I've also tried this:

(ReachabilityInst.currentReachabilityStatus() == ReachableViaWiFi)

But that results in xCode telling me "Could not find an overload for '==' that accepts the supplied arguments", even though both appear to be of type 'NetworkStatus'.

Thanks in advance.

Answer

Nate Cook picture Nate Cook · Jul 12, 2014

The Reachability class you're using is based on Apple's SCNetworkReachability class, which doesn't do exactly what you're hoping. From the SCNetworkReachability documentation:

A remote host is considered reachable when a data packet, sent by an application into the network stack, can leave the local device. Reachability does not guarantee that the data packet will actually be received by the host.

So it's not built for testing whether or not the remote host is actually online, just whether (1) the current network settings will allow an attempt to reach it and (2) by what methods. Once you've determined that the network is active you'll need to make an attempt to connect to see if the remote host is actually up and running.


Note: This test:

(ReachabilityInst.currentReachabilityStatus().value == ReachableViaWiFi.value)

is the correct way to check -- for some reason NetworkStatus is one of the few Apple enumerations created without the NS_ENUM macro.