Skip to content

Instantly share code, notes, and snippets.

@Sharkesm
Last active December 10, 2017 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sharkesm/ab9e87acbc4507c89d26c624b07d3d29 to your computer and use it in GitHub Desktop.
Save Sharkesm/ab9e87acbc4507c89d26c624b07d3d29 to your computer and use it in GitHub Desktop.
Network Reachability In Swift

Network Reachability In Swift

As for some new Swift programmers, they may had faced this issue before and it's really a headache when you spend hours searching for a better practice online to deploy into your code. Well since it's a major issue for some, i thought of sharing some code pieces that i think would help someone else out there and now lets move on with the coding part not good of a writer though 😅.

Frameworks Needed

So basically you have to integrate the above frameworks into your Xcode project and i'm hoping you know how to do that as i won't be going through that topic with cocoapods for now.

Now Moving on with the coding, I created a new swift file named "TRAReachability" you may proceed naming it however you may want not an issue for now as long it's understoodable with the rest of your team mates.

Below is the coding part of the named file:

//
//  TRAReachability.swift
//  Trasso
//
//  Created by Sharkes Monken on 10/12/2017.
//  Copyright © 2017 Sharkes Monken. All rights reserved.
//

import Foundation
import PopupDialog
import Alamofire

class TRAReachability {

    private var currentViewController : UIViewController? = nil
    private var popup : PopupDialog? = nil

    //shared instance
    static let shared = TRAReachability()
    let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.com")


    /**

     Configure current view controller as a network observer

     **/
    public func currentViewController(_ vc: UIViewController?) {
        self.currentViewController = vc
        self.startNetworkReachabilityObserver() // Start network observer 
    }

    /**

      Presents an alert dialog box notifying the users concerning the network issues 

    **/
    private func presentReachabilityPopup() {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3.5) {
            self.popup = PopupDialog(title: "Connectivity Issues", message: "Oops, it seems you have lost connection, please check your internet connection.")
            let settingButton = DefaultButton(title: "Settings", action: {
                if let url = URL(string:"App-Prefs:root=Settings&path=General") {
                    UIApplication.shared.open(url)
                }
            })
            self.popup?.addButton(settingButton)
            if self.currentViewController != nil {
                self.currentViewController?.present(self.popup!, animated: true, completion: nil)
            }
        }
    }

    public func stopNetworkReachabilityObserver() {
        reachabilityManager?.stopListening()
    }


    /**

     Starts network observer and manages to listen on different kind of network
     changes. Popup warning dialogs will be presented based on different kind of network status
     such as network is not reachable and once network resorts back online defined popup dialog will
     be dismissed automatically.

     **/
    public func startNetworkReachabilityObserver() {

        if let status = reachabilityManager?.isReachable, status == false {
            if self.currentViewController != nil {
                self.currentViewController?.hideProgressHUD() // Don't mind about this line 
            }
            self.presentReachabilityPopup()
            return
        }

        reachabilityManager?.listener = { status in
            switch status {
            case .notReachable:
                if self.currentViewController != nil {
                    self.currentViewController?.hideProgressHUD() // Don't mind about this line 
                    self.presentReachabilityPopup()
                }
                break
            case .unknown :
                break
            case .reachable(.ethernetOrWiFi), .reachable(.wwan):
                if self.popup != nil ,self.currentViewController != nil {
                    self.popup?.dismiss()
                }
                break
            }
        }

        // start listening
        reachabilityManager?.startListening()
    }
}

Quick explaination; The above piece of code act as a singleton class mainly with a purpose of observing network current status. So in order for different view controllers to listen for network status changes i decided to have an open method to configure the current view controller that is active and should listen for any network changes "currentViewController" method. Once that view controller is configured network listener will be started "startNetworkReachabilityObserver" method, but before observing network status begins it checks for current status if it's unreachable if does present an alert dialog or else start monitoring network status for further changes. "startNetworkReachabilityObserver" method kind solve the main issue of alerting and auto dismiss of alert dialog now imagine the network suddenly goes off "unreachable" while using the app this method will present an alert dialog but when the network suddenly comes back online "reachable" while the user is still using the app it will dismiss the alert dialog.

TRAReachability Usage

Since the class above is a singleton class, we can proceed calling it from anywhere through out our app. On view did load i had to invoke some few methods from TRAReachability as below to observer network reachability and thats all nothing crazy:

class ViewController : UIViewController {
	     	override func viewDidLoad() {
         	super.viewDidLoad()
         	// Configure reachability observer on this controller
         	TRAReachability.shared.currentViewController(self)
	   }
}

Stop Reachability

Two ways to stop reachability observer either calling "stopNetworkReachabilityObserver" method when a particular view controller that happens to be listening is about to be destroyed or when the app is about enter into the background by doing this it gives the app flexibility. For example:

// AppDelegate.swift file 

internal func applicationDidEnterBackground(_ application: UIApplication) {
       TRAReachability.shared.stopNetworkReachabilityObserver() // Stop network observer 
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment