Reputation: 458
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.
Upvotes: 0
Views: 566
Reputation: 658
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 {
}
Upvotes: 2