Detecting Network Connectivity Changes using Reachability, NSNotification and Network Link Conditioner in Swift Detecting Network Connectivity Changes using Reachability, NSNotification and Network Link Conditioner in Swift ios ios

Detecting Network Connectivity Changes using Reachability, NSNotification and Network Link Conditioner in Swift


You must create a Reachability object before you can receive notifications from it. Also, be sure to call the startNotifier() method on the Reachability object you create. This would be an example of how to do so inside of your application delegate:

class AppDelegate: UIResponder, UIApplicationDelegate{    private var reachability:Reachability!;    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool    {        NSNotificationCenter.defaultCenter().addObserver(self, selector:"checkForReachability:", name: kReachabilityChangedNotification, object: nil);        self.reachability = Reachability.reachabilityForInternetConnection();        self.reachability.startNotifier();    }    @objc func checkForReachability(notification:NSNotification)    {        // Remove the next two lines of code. You cannot instantiate the object        // you want to receive notifications from inside of the notification        // handler that is meant for the notifications it emits.        //var networkReachability = Reachability.reachabilityForInternetConnection()        //networkReachability.startNotifier()        let networkReachability = notification.object as Reachability;        var remoteHostStatus = networkReachability.currentReachabilityStatus()        if (remoteHostStatus.value == NotReachable.value)        {            println("Not Reachable")        }        else if (remoteHostStatus.value == ReachableViaWiFi.value)        {            println("Reachable via Wifi")        }        else        {            println("Reachable")        }    }}

I recommend you take a look at the documentation for NSNotificationCenter and NSNotification. That way you'll be more familiar with how to work with notifications next time something like this comes up.

Swift 3

NotificationCenter.default.addObserver(self, selector:Selector(("checkForReachability:")), name: NSNotification.Name.reachabilityChanged, object: nil)let reachability: Reachability = Reachability.forInternetConnection()reachability.startNotifier()


Updated for Swift 4 / Swift 5 according @Hardik.T

1. Import Reachability.swift file from https://github.com/ashleymills/Reachability.swift/archive/master.zip in your XCode project

2. Create a new Swift class : ConnectionManager.swift

class ConnectionManager {static let sharedInstance = ConnectionManager()private var reachability : Reachability!func observeReachability(){    self.reachability = Reachability()    NotificationCenter.default.addObserver(self, selector:#selector(self.reachabilityChanged), name: NSNotification.Name.reachabilityChanged, object: nil)    do {        try self.reachability.startNotifier()    }    catch(let error) {        print("Error occured while starting reachability notifications : \(error.localizedDescription)")    }}@objc func reachabilityChanged(note: Notification) {    let reachability = note.object as! Reachability    switch reachability.connection {    case .cellular:        print("Network available via Cellular Data.")        break    case .wifi:        print("Network available via WiFi.")        break    case .none:        print("Network is not available.")        break    case .unavailable:        print("Network is  unavailable.")        break    }  }}

3. Use it in your AppDelegate file :

func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {    ConnectionManager.sharedInstance.observeReachability()    return true}


Instead of polluting the AppDelegate.swift with observer callbacks I would recommend adding observers only into the relevant view controllers.

AppDelegate.swift

import ReachabilitySwift@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate{    var reachability: Reachability?    func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? ) -> Bool    {       self.reachability = Reachability()       do       {          try reachability?.startNotifier()       }       catch       {          print( "ERROR: Could not start reachability notifier." )       }       return true    }    class func sharedAppDelegate() -> AppDelegate?    {        return UIApplication.shared.delegate as? AppDelegate    }    // Remaining functions}

Example of a ViewController:

class ExampleVC: UIViewController{    override func viewDidLoad()    {        // Add reachability observer        if let reachability = AppDelegate.sharedAppDelegate()?.reachability        {            NotificationCenter.default.addObserver( self, selector: #selector( self.reachabilityChanged ),name: ReachabilityChangedNotification, object: reachability )        }    }    @objc private func reachabilityChanged( notification: NSNotification )    {        guard let reachability = notification.object as? Reachability else        {            return        }        if reachability.isReachable        {            if reachability.isReachableViaWiFi            {                print("Reachable via WiFi")            }            else            {                print("Reachable via Cellular")            }        }        else        {            print("Network not reachable")        }    }}