Search code examples
iosswiftreachability

How can i dismiss view controller if internet connected


i am trying to dismiss view controller if internet connected. When there is no internet it present my noInternetViewController but when i reconnect to internet, noInternetViewController view didnt dismissed.

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: ReachabilityChangedNotification, object: reachability)
}

func reachabilityChanged(note: NSNotification) {
    let reachability = note.object as! Reachability

    if reachability.isReachable {
        if noInternet == true {
            DispatchQueue.main.async {
                self.noInternet = false
                self.dismiss(animated: true, completion: nil)
            }
        }
    } else {
        noInternet = true
        if noInternet == true {
            DispatchQueue.main.async {
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let noInternetViewController = storyboard.instantiateViewController(withIdentifier: "NoInternetViewController") as! NoInternetViewController
                noInternetViewController.modalPresentationStyle = UIModalPresentationStyle.overFullScreen
                self.present(noInternetViewController, animated: true, completion: nil)
            }
        }

    }
}

And NoInternetViewController:

import UIKit

class NoInternetViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

Thanks for your helps


Solution

  • In your NoInternetViewController, you can add a Observer to it as well. When you received connection, post a notification to trigger it's selector to dismiss itself.

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(receivedConnection), name: NSNotification.Name.init(rawValue: "ReceivedConnection"), object: nil)
    }
    
    func receivedConnection() {
        self.dismiss(animated: true, completion: nil)
    }