Handle Internet Connectivity - iOS

Network

Protocol oriented and clean way of internet connectivity control

The main idea of this example is the adapt the basic to swifts protocol-oriented strategy.

Reachability.swift is a replacement for Apple’s Reachability sample, re-written in Swift with closures. Here.

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'ReachabilitySwift'

After implemented the pod run this code in terminal

pod install
  1. First of all, we create our first file Reachable.swift.This file contains a protocol named Reachable

Parameter: status → is a type of Reachability. Connection enum

2. Then we create our file Reachable + Notification.swift.The file contains an extension for the Reachable protocol.

Basically, it does all the job after implementation of this Reachable protocol to the view controllers.

self?.reachabilityChanged(status: reachability.connection)

Returns the connectivity status enum to implemented classes.

Firstly be sure that your view controller, cell, etc. has implemented the Reachable Protocol

class ViewController: Reachable {

after implement the reachabilityChanged(status:) function

func reachabilityChanged(status: Reachability.Connection) {
if status == .cellular || status == .wifi{
print("connected")
}else if status == .unavailable{
print("disconnect")
}
}

Secondly, in your view controller, call this function to activate the observing.

func viewDidLoad() {        
startObservingReachability()
}
Usage

Test it out. The function will be called when the first initialization and when the connectivity changed. Now you can use easily when you want to perform tasks connected to reachability.

Ask anything on comments. Thank you for your time.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store