简体   繁体   中英

How do I check from a view controller or class if a specific view controller is visible on screen? Or how do I check visible view controller?

In my app I have a chat view controller. When this controller is presented (visible on screen) I don't want to receive push notifications from firebase. Otherwise yes. I handle the notifications in a separate class, in which I want to do something like this, but I don't have access to that variable, neither to an instance of that chat controller :

If !ChatViewController.isOnScreen {
    sendPushNotification()
}

A created an extension, but I don't know why I can't use it. This is it:

extension UIViewController {
    public var isOnScreen: Bool {
        if isViewLoaded {
            return view.window != nil
        }
        return false
    }

    public var isTopViewController: Bool {
        if self.navigationController != nil {
            return self.navigationController?.visibleViewController === self
        } else if self.tabBarController != nil {
            return self.tabBarController?.selectedViewController == self && self.presentedViewController == nil
        } else {
            return self.presentedViewController == nil && self.isOnScreen
        }
    }
}

How can I do this? Thanks in advance.

If you don't have that view controller's instance, what you can do is to create a statice variable in the view controller and set that to true when the controller is visible and false when it is invisible.
Here's some sample code. In your ChatViewController

public static var isOnScreen = false

override func viewDidAppear(_ animated: Bool) {
  super.viewDidAppear(animated)
  isOnScreen = true
}

override func viewDidDisappear(_ animated: Bool) {
  super.viewDidDisappear(animated)
  isOnScreen = false
}

Now you can check this variable any time to know if the controller is visible or not like this.

if ChatViewController.isOnScreen {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM