How to continuously appear alert while there is no internet connection?

1.5k views Asked by At

I am working on an iOS app that requires internet connection to run properly so i'm using the Reachability framework so that I can obtain the connection state. Right now whenever there is no internet connection I have and alert with the button saying "Try Again" showing up once and what I want it's the alert to be continuously appear while there's no internet. Can you help me please? Thanks!

By the way, if you think there is something I should change go ahead and tell me! Cheers!

class ViewController: UIViewController {

let reachability = Reachability()!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func viewDidAppear(_ animated: Bool) {

    reachability.whenReachable = { reachability in
        if reachability.connection == .wifi {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
    }
    reachability.whenUnreachable = { _ in
        print("Not reachable")
    }

    do {
        try reachability.startNotifier()
    } catch {
        print("Unable to start notifier")
    }

    NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
    do{
        try reachability.startNotifier()
    }catch{
        print("could not start reachability notifier")
    }
}

@objc func reachabilityChanged(note: Notification) {

    let reachability = note.object as! Reachability

    switch reachability.connection {
    case .wifi:
        print("Reachable via WiFi")
    case .cellular:
        print("Reachable via Cellular")
    case .none:
        print("Network not reachable")
        createAlert(title: "No Internet Connection", message: "Internet Connection is required fot this application to run properly")
    }
}

func createAlert(title:String, message:String)
{
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)

    alert.addAction(UIAlertAction(title: "Try Again", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated: true, completion: nil) } ) )

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

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}
1

There are 1 answers

2
Eric D'Souza On

Instead of an alert, it might be better to use a label that is hidden, and un-hidden when there is no internet. then hide again once the connection is back