Pinging a Host for Reachability

In this lesson

Pinging a host for its reachability in Alamofire is really simple and is a great to check whether the host you are using is online or accessible and that the current device has internet access. If the reachability does change, you will be notified and can respond accordingly depending on the connection type and network status of the host and device.

Kyle Roberts
Swift Guru at Large

Kyle's Series

Transcript

Tap on time to skip ahead

0:11

Intro

Kyle here, let’s talk about a way to assess the reachability of a host with Alamofire. When you import Alamofire, you have access to this class NetworkReachabilityManager. On the initialization of this manager, you pass in a string URL of the host that you’re working with. And in this case, I’m working with Steam store – since of course, this app steam reader is all about, you know, different apps in the Steam store. 

0:38

Pinging to Assess Reachability

But all we need to do t0 ping this host – and to periodically assess its reachability – is to set a listener closure on this reachability manager. You do that just by setting the listener property to a new closure – it passes in a variable of the network status. All I’m doing at the moment is printing that status to the log whenever it changes. And then after you’ve set the listener, you want to tell the manager to start listening. That just means that it will start paying attention to the host we specified. And of course will relay any changes in the reachability of the host to the listener, which we have specified above. 

1:22

Reachability Types

To show the available reachability types that you may encounter, there is an enum called NetworkReachabilityStatus with 2 cases unknown and not reachable. And then a third case with a corresponding value called reachable. And that’s the type of the status parameter here. So then once we’re actually listening to changes in the reachability status of our host, we can use a simple switch statement just to determine whether the host is reachable or not. And with the switch statement I’m just checking in the first case whether the included status is reachable or not. And otherwise we’re just going to print that Steam is unreachable at this time. But if it is reachable, we’ll say Steam is available. And this warning is just complaining that I’m not using this connection type reference here. But I just wanted to demonstrate that this is what you’ll do if you are using the connection type – and of course Swift wanted us to change that to an underscore just because it’s an unused variable at this time. And that’s how you ping your host and watch for changes in its reachability.