0

Currently I implemented the Reachability is AppDelegate.swift file. This is my code to determine when I connect or disconnect to the internet

@objc func reachabilityChanged(note: Notification) {
    let reachability = note.object as! Reachability
    if (reachability.connection != .none) {
    }
    else
    {
        currentView()
    }

}

This code works fine to detect if the internet is connected or disconnected. Now if the internet is disconnected I want to know which viewController I am currently at in my navigationController and I would like to modify the UI of that viewController to notify the user that the Internet Is disconnected. I am trying to get the current viewController in my navigationStack using the following code but it does not work

if let window = UIApplication.shared.delegate?.window {
    if var viewController = window?.rootViewController {
        // handle navigation controllers
        if(viewController is UINavigationController){
            viewController = (viewController as! UINavigationController).visibleViewController!
        }
        print (viewController)
    }
}
Ahmed
  • 1,229
  • 2
  • 20
  • 45
  • Why do you need the name? What is are you to accomplish? BTW - `type(of:)`. – rmaddy May 28 '18 at 22:24
  • I need to know which view controller is active so I can execute certain function specific to each view controller – Ahmed May 28 '18 at 22:26
  • 1
    OK but getting its name is not the correct approach. Use `is` or `if let as?`. – rmaddy May 28 '18 at 22:26
  • you mean I should use viewController is (className) and check ? – Ahmed May 28 '18 at 22:28
  • That's one solution. The best solution depends on what you really need to do once you know what type of view controller it is but you haven't explained that in your question. – rmaddy May 28 '18 at 22:32
  • Ok I have a function that determines if I am connected or not using reachability in AppDelegate.swift. If the Internet is disconnected I want to know Which UIViewController I am currently at and based on that I want to modify UI of that ViewController to basically say to the user that the connection is lost – Ahmed May 28 '18 at 22:39
  • You need to [edit] your question with all relevant details. – rmaddy May 28 '18 at 22:40

1 Answers1

1

I would suggest you use NotificationCenter and send a notification to the observers to do what you want if their view is on screen. Make your VCs observers and implement selectors when notification is sent.

Check this answer if you don't know how to check if the view is on screen: How to tell if UIViewController's view is visible

Snezhana
  • 100
  • 8