iosswiftreachability

How to test reachability in iOS and retry to connect?


I want to test reachability when users lost connection when they are Logged and prompt them to try to connect again.

first, I try using when unreachable closure and show UIalert says "Please check your internet connection and try again." with "Retry" action to try retry to test the connection if not connection shows the message else "have a connection " remove the UI alert.

import UIKit

class BaseTabBarViewController: UITabBarController {

    let network = NetworkManager.sharedInstance

    override func viewDidLoad() {
        super.viewDidLoad()

        network.reachability.whenUnreachable = { reachability in
            self.showOfflinePage()
        }
    }

    func retryConnection(alert: UIAlertAction!){
        print("test connection ")
        // if no connction found show try agine
        //else connction

    }

    func showOfflinePage(){

        DispatchQueue.main.async {
            // create the alert
            let alert = UIAlertController(title: "Connectivity Error", message: "Please check your internet connection and try again.", preferredStyle: UIAlertController.Style.alert)

            // add an action (button)
            alert.addAction(UIAlertAction(title: "Retry", style: UIAlertAction.Style.default, handler: self.retryConnection))

            // show the alert
            self.present(alert, animated: true, completion: nil)
        }
    }
}

Solution

  • There are bunch of reachability pods available. One of the most used is Alamofire. Here are the links to the repo and an example of how to use it.

    https://github.com/Alamofire/Alamofire/blob/master/Source/NetworkReachabilityManager.swift

    https://medium.com/@abhimuralidharan/checking-internet-connection-in-swift-3-1-using-alamofire-58ae45719f5