---
title: "#111: Reachability.swift 📡"
url: https://littlebitesofcocoa.com/111-reachability-swift
author: Jake Marsh
published: 2015-10-26
topics: ["Libraries","Networking"]
description: "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..."
---

# #111: Reachability.swift 📡

By Jake Marsh, October 26, 2015. HTML: https://littlebitesofcocoa.com/111-reachability-swift

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](https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html) 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](https://github.com/ashleymills) called [Reachability.swift](https://github.com/ashleymills/Reachability.swift) that aims to make this less painful. Let's begin.

We'll start by trying to create a new _Reachability_ object:

``` swift
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**.

``` swift
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:

``` swift
do { try reachability.startNotifier() } catch {
  print("ERROR: Unable to start Reachability notifier")
  assumeConnectivity()
}
```

Then stop it later with:

``` swift
reachability.stopNotifier()
```

It's important to consider if our **app** <i>even needs</i> 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.

<i>Note:</i> We looked at the simple **closure** syntax here, but [Reachability.swift](http://git.io/reachability) 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](http://git.io/reachability)
