I am on ChatViewController
and i navigated to some other page and again i visited to ChatViewController
so how can i check im on ChatViewController
page or not when i visit same page.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
UserDefaults.standard.value(forKey: "ChatView")
print("view will appear called")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
UserDefaults.standard.object(forKey: "ChatView")
print("view will disappear called")
}
Do i need to set any UserDefaults
value or some other thing.Could some one help me in this.Thanks in advance
Swift 5 and iOS 15
if self.navigationController?.presentedViewController != nil &&
self.navigationController?.presentedViewController is ChatViewController {
return
}
You can check the navigation stack of your current navigation controller.
let viewControllers = self.navigationController!.viewControllers as [UIViewController]
for vc:UIViewController in viewControllers {
if vc.isKind(of: YourVC.self) {
}
}
It would make no sense to use user defaults because those will be persistent even if your app is killed. That means if user is on chat, closes the app, opens it again your user defaults value will say user is still on the chat screen.
There are multiple ways of showing your chat screen. It might be presented, might be pushed in navigation bar, inside tab bar or even custom added to content view. So I would say it is still best to use willAppear
and didDisappear
. A static value should do the trick:
class ChatViewController: UIViewController {
static private(set) var currentVisibleInstance: ChatViewController?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
ChatViewController.currentVisibleInstance = self
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
ChatViewController.currentVisibleInstance = nil
}
}
Now you can use this from anywhere:
let isChatVisible: Bool = ChatViewController.currentVisibleInstance != nil
let currentChatController: ChatViewController? = ChatViewController.currentVisibleInstance
Naturally you could put this currentVisibleInstance
in some other class if you see fit. You would simply change to SomeOtherClass.currentVisibleChatViewController = self
.
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.