Network reachability status monitoring on iOS (Part 1)

Sauvik Dolui
5 min readOct 18, 2016

--

Network reachability status monitoring on popular apps

Now-a-days you will hardly find an application which does not require any server side support to perform its tasks. As the days progress, almost all apps are collecting data from iOS applications and saving them in remote server for providing better cloud based services to its users. All cloud based applications needs to monitor network connectivity status to provide a better UX to its users. We can find them in Mail, Safari, App Store, Test Flight, Google Drive, Skype and so on.

You might have handled such scenarios using Reachability Objective-C class by Apple. You might be wishing to have a Swift solution for that. Am I right? Yes? Take a deep breath, you are on your marks.

You need a good start:

Create a new Single View Application in Xcode named NetworkStatusMonitor. We will be using Reachability swift library created by Ashley Mills. Thank you @ashleymills for this useful library. The most popular way to integrate such libraries in iOS is CocoaPods. If you have not used this tool before, please go through this to install CocoaPods on your system.

Now from the terminal, change the directory path to your project’s root directory.

Move to your project’s root directory

Now we will initialize pods with the following command in Terminal

pod init

It creates a simple pod file in your project’s root directory.

Pod file

Open this pod file in TextEdit, edit and save it with the following content.

# Uncomment this line to define a global platform for your project
# platform :ios, ‘9.0’
target ‘NetworkStatusMonitor’ do
# Comment this line if you’re not using Swift and don’t want to use dynamic frameworks
use_frameworks!
# Pods for NetworkStatusMonitor
pod ‘ReachabilitySwift’, ‘~> 3’ # Adds the library to your project
target ‘NetworkStatusMonitorTests’ do
inherit! :search_paths
# Pods for testing
end
target ‘NetworkStatusMonitorUITests’ do
inherit! :search_paths
# Pods for testing
end

Now go back to our 💚 terminal to do the rest for basic project setups. Run the following command from terminal to add the pod library.

pod install

If everything goes fine you will see similar output as the following one.

Pod installation for Reachability 3.0

It creates a new workspace for your project. As the installation says, we will close the Xcode project and open the NetworkStatusMonitor. xcworkspace for continuing the development.

Xcode Workspace after installing pods

Due to migration issues from in Swift versions, you might need to follow Xcode’s default conversion process. Just use the default selected options for that. You may end up with some compiler errors. For that you just need to clean (⌘ + K) your workspace and build (⌘ + B) it again. If you face any difficulty, please go back and make sure that you have followed each step carefully OR you can download the this starter project from GitHub.

Have some fun with code:

Now it’s time to write down some code. We will create a ReachabilityManager singleton instance, which will be monitoring network reachability continuously. So, let’s create ReachabilityManager as a new CocoaTouch subclass of NSObject.

We will import ReachabilitySwift and create a shared instance for that manager.

import UIKit
import ReachabilitySwift // 1. Importing the Library
class ReachabilityManager: NSObject { static let shared = ReachabilityManager() // 2. Shared instance}

We will need some extra data members in the class for tracking more information about the current network status.

// 3. Boolean to track network reachability
var isNetworkAvailable : Bool {
return reachabilityStatus != .notReachable
}
// 4. Tracks current NetworkStatus (notReachable, reachableViaWiFi, reachableViaWWAN)
var reachabilityStatus: Reachability.NetworkStatus = .notReachable
// 5. Reachability instance for Network status monitoring
let reachability = Reachability()!

Who will monitor?

Reachability instance (reachability) continuously fires ReachabilityChangedNotification whenever there is a change in the network reachability status. We will set up a function to listen to that notification. This notification will contain the reachability instance as an object.

/// Called whenever there is a change in NetworkReachibility Status
///
/// — parameter notification: Notification with the Reachability instance
func reachabilityChanged(notification: Notification) { let reachability = notification.object as! Reachability switch reachability.currentReachabilityStatus {
case .notReachable:
debugPrint(“Network became unreachable”)
case .reachableViaWiFi:
debugPrint(“Network reachable through WiFi”)
case .reachableViaWWAN:
debugPrint(“Network reachable through Cellular Data”)
}
}

Let’s start monitoring:

So the above function will get called each time when there is a change in network reachability status. But we have not registered for it yet. Let’s do that with the help of following function.

/// Starts monitoring the network availability status
func startMonitoring() {
NotificationCenter.default.addObserver(self,
selector: #selector(self.reachabilityChanged),
name: ReachabilityChangedNotification,
object: reachability)
do{
try reachability.startNotifier()
} catch {
debugPrint(“Could not start reachability notifier”)
}
}

The game begins right now:

Open func application(_:didFinishLaunchingWithOptions:) in AppDelegate.swift. Add the following code before return true statement to start the monitoring whenever the application launches.

ReachabilityManager.shared.startMonitoring()

Now run the application.

The result is here:

Final output of the project

If there is a start, there must be an end:

We may not wish to monitor network status when the application enters in background. The following function will stop monitoring network status changes in ReachabilityManager.

/// Stops monitoring the network availability status
func stopMonitoring(){
reachability.stopNotifier()
NotificationCenter.default.removeObserver(self,
name: ReachabilityChangedNotification,
object: reachability)
}

The Best Practice:

The best practice is to start monitoring when the application comes in the foreground and stop it when we do not need it any more. We can stop ReachabilityManager from monitoring the network reachability status change. We can do so in AppDelegate’s func applicationDidBecomeActive(_:) and func applicationWillEnterForeground(_:) respectively.

func applicationDidBecomeActive(_ application: UIApplication) {
// Starts monitoring network reachability status changes
ReachabilityManager.shared.startMonitoring()
}
func applicationWillEnterForeground(_ application: UIApplication){
// Stops monitoring network reachability status changes
ReachabilityManager.shared.stopMonitoring()
}

What Next?

The fully developed project is available from GitHub. In next part (Part 2) of this article, I will discuss how to create a protocol for that. Any UIViewController or AnyObject, implementing this protocol, can listen to network reachability status changes gracefully.

Promotions:

Don’t forget to read my previous blogs😏.

1. A Smart Way to Manage Colour Schemes for iOS Application Development.

2. Handling Fonts in iOS Development, a Simpler Way.

3. Developing a Tiny Logger in Swift.

4. Making a Stateful TableView for iOS.

5. A few git tricks & tips.

--

--