Topics

#111: Reachability.swift 📡

Topics

Mobile devices can lose or change connectivity state suddenly and unexpectedly. It's important for us to make our apps respond well and degrade gracefully when this occurs.

Reachability describes how "reachable" the Internet is at a given time. Apple has long offered sample code for dealing with Reachability, but the process has always been a bit of a nuisance.

Today we'll look at a great little library from Ashley Mills called Reachability.swift that aims to make this less painful. Let's begin.

We'll start by trying to create a new Reachability object:

let reachability: Reachability

do {
  reachability = try Reachability.reachabilityForInternetConnection()
} catch {
  print("ERROR: Unable to create Reachability")
  assumeConnectivity()
}

Then we'll set some closures on it that will be called when the Reachability state changes. These will be called on a background queue, so we'll hop to the main queue before updating any UI.

reachability.whenReachable = { reachability in
  dispatch_async(dispatch_get_main_queue()) { /* TODO */ }
}

reachability.whenUnreachable = { reachability in
  dispatch_async(dispatch_get_main_queue()) { /* TODO */ }
}

Now, we can tell the object to start listening for connectivity changes:

do { try reachability.startNotifier() } catch {
  print("ERROR: Unable to start Reachability notifier")
  assumeConnectivity()
}

Then stop it later with:

reachability.stopNotifier()

It's important to consider if our app even needs this functionality.

If possible, we should try to avoid degrading the experience at all when connectivity goes away. If this isn't possible, for example if our app is streaming live video, we should respond to the change in Reachability, and tell the user why playback was interrupted.

Note: We looked at the simple closure syntax here, but Reachability.swift has great support for NSNotificationCenter notifications as well as Wifi vs. Cellular detection.

More info about Reachability.swift can be found at git.io/reachability