single function to dismiss all open view controllers - ios

I have an app which is a single view application. I have a navigation controller linked up to all child controllers from the root view controller.
In each child controller, I have a logout button. I'm wondering if I can have a single function I can call which will dismiss all the controllers which have been open along along the way, no matter which controller was currently open when the user presses logout?
My basic start:
func tryLogout(){
self.dismissViewControllerAnimated(true, completion: nil)
let navigationController = UINavigationController(rootViewController: UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LoginViewController") )
self.presentViewController(navigationController, animated: true, completion: nil)
}
I am looking for the most memory efficient way of carrying out this task. I will put my logout function in a separate utils file, but then I can't use self. And I still have the issue of knowing which controllers to dismiss dynamically.
Update
Pop to root view controller has been suggested. So my attempt is something like:
func tryLogout(ViewController : UIViewController){
print("do something")
dispatch_async(dispatch_get_main_queue(), {
ViewController.navigationController?.popToRootViewControllerAnimated(true)
return
})
}
Would this be the best way to achieve what I'm after?

You can call :
self.view.window!.rootViewController?.dismiss(animated: false, completion: nil)
Should dismiss all view controllers above the root view controller.

Updated answer for Swift 4 and swift 5
UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: true, completion: nil)
and when you use navigationController
self.navigationController?.popToRootViewController(animated: true)

Works for Swift 4 and Swift 5
To dismiss any unwanted residue Modal ViewControllers, I used this and worked well without retaining any navigation stack references.
UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: false, completion: nil)
self.view.window! did crash for my case possibly because its a Modal screen and had lost the reference to the window.

Swift3
navigationController?.popToRootViewControllerAnimated(true)

Take a look at how unwind segues work. Its super simple, and lets you dismiss/pop to a certain viewcontroller in the heirarchy, even if it consists of a complex navigation (nested pushed and or presented view controllers), without much code.
Here's a very good answer (by smilebot) that shows how to use unwind segues to solve your problem
https://stackoverflow.com/a/27463286/503527

To dismiss all modal Views.
Swift 5
view.window?.rootViewController?.dismiss(animated: true, completion: nil)

If you have a customed UITabbarController, then try dismiss top viewController in UITabbarController by:
class MainTabBarController: UITabBarController {
func aFuncLikeLogout() {
self.presentedViewController?.dismiss(animated: false, completion: nil)
//......
}
}

If you have access to Navigation Controller, you can try something like this. Other solutions didn't work for me.
func popAndDismissAllControllers(animated: Bool) {
var presentedController = navigationController?.presentedViewController
while presentedController != nil {
presentedController?.dismiss(animated: animated)
presentedController = presentedController?.presentedViewController
}
navigationController?.popToRootViewController(animated: animated)
}

works for Swift 3.0 +
self.view.window!.rootViewController?.dismiss(animated: true, completion: nil)

I have figured out a generic function to dismiss all presented controllers using the completion block.
extension UIWindow {
static func keyWindow() -> UIWindow? {
UIApplication.shared.windows.filter({ $0.isKeyWindow }).first
}
}
func getVisibleViewController(_ rootViewController: UIViewController?) -> UIViewController? {
var rootVC = rootViewController
if rootVC == nil {
rootVC = UIWindow.keyWindow()?.rootViewController
}
var presented = rootVC?.presentedViewController
if rootVC?.presentedViewController == nil {
if let isTab = rootVC?.isKind(of: UITabBarController.self), let isNav = rootVC?.isKind(of: UINavigationController.self) {
if !isTab && !isNav {
return rootVC
}
presented = rootVC
} else {
return rootVC
}
}
if let presented = presented {
if presented.isKind(of: UINavigationController.self) {
if let navigationController = presented as? UINavigationController {
return navigationController.viewControllers.last!
}
}
if presented.isKind(of: UITabBarController.self) {
if let tabBarController = presented as? UITabBarController {
if let navigationController = tabBarController.selectedViewController! as? UINavigationController {
return navigationController.viewControllers.last!
} else {
return tabBarController.selectedViewController!
}
}
}
return getVisibleViewController(presented)
}
return nil
}
func dismissedAllAlert(completion: (() -> Void)? = nil) {
if let alert = UIViewController.getVisibleViewController(nil) {
// If you want to dismiss a specific kind of presented controller then
// comment upper line and uncomment below one
// if let alert = UIViewController.getVisibleViewController(nil) as? UIAlertController {
alert.dismiss(animated: true) {
self.dismissedAllAlert(completion: completion)
}
} else {
completion?()
}
}
Note: You call anywhere in code at any class
Use:-
dismissedAllAlert() // For dismiss all presented controller
dismissedAllAlert { // For dismiss all presented controller with completion block
// your code
}

Swift
Used this to jump directly on your ROOT Navigation controller.
self.navigationController?.popToRootViewController(animated: true)

Related

Swift iOS - how to properly use popToViewController

it's again me - learning swift.
Question is simple, i have control views like this:
[Initial]->[NotLogged]->[SignUp]
Now after sign up i have double dismiss, it's really ugly!
I wan't to go straight from SignUp to Initial page.
I tried this code but sadly it closing app without any error.
self.dismiss(animated: true, completion: {
let controllers = self.navigationController?.viewControllers
for vc in controllers! {
if vc is InitialViewController {
_ = self.navigationController?.popToViewController(vc as! InitialViewController, animated: true)
}
}
} )
pushViewController works same as above, there is output:
2020-01-29 20:30:38.342180+0100 BillyBill[44355:19540995] Can't end
BackgroundTask: no background task exists with identifier 10 (0xa), or
it may have already been ended. Break in
UIApplicationEndBackgroundTaskError() to debug.
Simply just pop to root view controller
self.navigationController?.popToRootViewController(animated: true)
You can just use self.navigationController?.popToRootViewController() command in place of
for vc in controllers! {
if vc is InitialViewController {
_ = self.navigationController?.popToViewController(vc as! InitialViewController, animated: true)
}
}

Swift Deeplink to already open App's already open viewcontroller?

I have an app that accepts a Deeplink URL and opens a viewcontroller with variables from the link and it works well if the App is opened/run for the first time by the user using the Deeplink.
However, if the App is already open/or in the background and has that view controller open... it then opens the same viewcontroller back up again so then I have two. I do not want to open the viewcontroller an additional time.
Is there some way I can identify that viewcontroller that is already open and pass the variables from the Deeplink to it?
or do I need to close it in some way and re-open it?
I am open to suggestions.... thanks in advance.
Try using UIApplication.shared.keyWindow?.rootViewController and testing what class it is. For example:
if let vc = UIApplication.shared.keyWindow?.rootViewController {
if vc is SomeViewController {
// Do something.
}
}
You can find the visible view controller with the following method
func getVisibleViewController(_ rootViewController: UIViewController?) -> UIViewController? {
var rootVC = rootViewController
if rootVC == nil {
rootVC = UIApplication.shared.keyWindow?.rootViewController
}
if rootVC?.presentedViewController == nil {
return rootVC
}
if let presented = rootVC?.presentedViewController {
if presented.isKind(of: UINavigationController.self) {
let navigationController = presented as! UINavigationController
return navigationController.viewControllers.last!
}
if presented.isKind(of: UITabBarController.self) {
let tabBarController = presented as! UITabBarController
return tabBarController.selectedViewController!
}
return getVisibleViewController(presented)
}
return nil
}
you can then switch on the presented view
if let presentedView = getVisibleViewController(window?.rootViewController) {
switch presentedView {
//code
default:
//code
}
}
and of course in the switch present a view controller if it is not the one that you want to be open.
No need to close a viewcontroller before opening it!

How to push user to ViewController from non UIView class [duplicate]

This question already has answers here:
How to launch a ViewController from a Non ViewController class?
(7 answers)
Closed 5 years ago.
I would like to know how can I push user back to specific ViewController from regular swift class without being non UIView Class
Example
class nonUI {
function Push() {
//How to send user back to specific VC here?
}
}
This is a generic method you can use with in the class or outside the class for push if required else it will pop if the instance of view controller is in the stack:
func pushIfRequired(className:AnyClass) {
if (UIViewController.self != className) {
print("Your pushed class must be child of UIViewController")
return
}
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var isPopDone = false
let mainNavigation = UIApplication.shared.delegate?.window??.rootViewController as? UINavigationController
let viewControllers = mainNavigation!.viewControllers
for vc in viewControllers {
if (type(of: vc) == className) {
mainNavigation?.popToViewController(vc, animated: true)
isPopDone = true
break
}
}
if isPopDone == false{
let instanceSignUp = storyboard.instantiateViewController(withIdentifier: NSStringFromClass(className)) // Identifier must be same name as class
mainNavigation?.pushViewController(instanceSignUp, animated: true)
}
}
USES
pushIfRequired(className: SignupVC.self)
You could also utilise the NotificationCenter to achieve a loosely coupled way to "request a view controller"; if you will.
For example, create a custom UINavigationController that observes for the custom Notification and upon receiving one, looks for the requested UIViewController and pops back to it.
class MyNavigationController : UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(forName: NSNotification.Name("RequestViewController"), object: nil, queue: OperationQueue.main) { [unowned self] (note) in
guard let targetType = note.object as? UIViewController.Type else {
print("Please provide the type of the VC to display as an `object` for the notification")
return
}
// Find the first VC of the requested type
if let targetVC = self.viewControllers.first(where: { $0.isMember(of: targetType) }) {
self.popToViewController(targetVC, animated: true)
}
else {
// do what needs to be done? Maybe instantiate a new object and push it?
}
}
}
}
Then in the object you want to go back to a specific ViewController, post the notification.
#IBAction func showViewController(_ sender: Any) {
NotificationCenter.default.post(Notification(name: NSNotification.Name("RequestViewController"), object: ViewController2.self))
}
Now, it's also fairly easy to adopt this method for other presentation-styles.
Instead of using the NotificationCenter, you could also muster up a Mediator to achieve the loose coupling.
You can't. UIViewController and its subclass only can handle navigate between screen.
In your case, need pass link (variable) to navigation controller in custom class.
Like:
class nonUI {
var navigationController: UINavigationController?
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
function Push() {
//How to send user back to specific VC here?
navigationController?.popViewController(animated: true)
}
}

How do I prevent a navigationController from returning to root when dismissing MFMailComposeViewController

When I dismiss an instance of MFMailComposeViewController or MFMessageComposeViewController that is presented modally from the third viewController in a navigation stack, the navigation stack is reset, and the root VC is reloaded. How can I prevent this behavior and remain on the original presenting viewController (third VC in the stack)? I get the same behavior whether I call dismiss from the presenting VC, the presented VC, or the navigationController.
This has been asked before, but I have not seen a solution.
App Structure looks like this:
TabBarController
Tab 1 - TripsNavController
-> Trips IntroductionVC (root VC) segue to:
-> TripsTableViewController segue to:
-> TripEditorContainerVC
- TripEditorVC (child of ContainerVC)
- HelpVC (child of ContainerVC)
Tab 2...
Tab 3...
Tab 4...
In the TripEditorVC I present the MFMailComposeViewController. The functions below are declared in an extension to UIViewController that adopts the MFMailComposeViewControllerDelegate protocol
func shareWithEmail(message: NSAttributedString) {
guard MFMailComposeViewController.canSendMail() else {
showServiceError(message: "Email Services are not available")
return
}
let composeVC = MFMailComposeViewController()
composeVC.setSubject("My Trip Plan")
composeVC.setMessageBody(getHTMLforAttributedString(attrStr: message), isHTML: true)
composeVC.mailComposeDelegate = self
present(composeVC, animated: true, completion: nil)
}
Then in the delegate method I dismiss the MFMailComposeVC:
public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
switch result {
case .sent:
print("Mail sent")
case .saved:
print("Mail saved")
case .cancelled:
print("Mail cancelled")
case .failed:
print("Send mail failed")
}
if error != nil {
showServiceError(message: "Error: \(error!.localizedDescription)")
}
dismiss(animated: true, completion: nil)
}
I have tried the following to present and dismiss and get the same behavior, i.e.: the TripsNavController clears the nav stack and reloads the TripsIntroductionVC as its root VC:
self.present(composeVC, animated: true, completion: nil)
self.parent?.present(composeVC, animated: true, completion: nil)
self.parent?.navigationController?.present(composeVC, animated: true, completion: nil)
self.navigationController?.present(composeVC, animated: true, completion: nil)
You can also check with presentingViewController?.dismiss method to get the solution.
I have tried with following navigation stack.
I am able to send email successfully from Container VC's Send Email button using your code only.
Can you please check and verify navigation flow?
Please let me know if you still face any issue.
dismiss(animated: true, completion: nil)
to
self.dismiss(animated: true, completion: nil)
Try this
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewControllerWithIdentifier("secondViewControllerId") as! SecondViewController
self.presentViewController(secondViewController, animated: true, completion: nil)
or
https://stackoverflow.com/a/37740006/8196100
Just Use Unwind Segue its Pretty simple and perfect in your case
I have used many times..
just look at this Unwind segue's example
. If u still don't able to find answer or not able to understand the Unwind segue then just reply to me.
Hope this will solve your problem.
I found the problem with my navigation stack today. I built a simple
project that duplicated the tabBarController/NavigationControler architecture of my problem project, component by component, until dismissing a MFMailComposeViewController caused my navigation stack to reset as described in my original post.
That immediately pointed to the source of the bug. In my subclassed UINavigationCotroller I was instantiating the root viewController in code so that I could skip an introductory view if the user had set a switch in the apps settings. In order to pick up changes in that switch setting I was calling my instantiation code in viewDidAppear of the navigationController. That worked fine EXCEPT when dismissing the mailComposeVC. The fix was to add a guard statement in viewDidAppear to return if the navControllers viewController collection was not empty, and send and respond to an NSNotification when the switch was changed.
class TopNavigationController: UINavigationController {
var sectionType: SectionType?
var defaults = UserDefaults.standard
var showIntroFlag: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
// Handle initial load of the tab bar controller where we are not sent a sectionType
if sectionType == nil {
sectionType = .groups
}
setShowIntroFlag()
NotificationCenter.default.addObserver(self, selector: #selector(resetControllers), name: NSNotification.Name(rawValue: "kUserDidChangeShowIntros"), object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
guard self.viewControllers.isEmpty else {
return
}
loadControllers()
}
func setShowIntroFlag() {
showIntroFlag = true
// Check NSUserDefaults to see if we should hide the Intro Views for all sections
if defaults.bool(forKey: "SHOW_SECTION_INTROS") == false {
showIntroFlag = false
}
}
func loadControllers() {
if showIntroFlag == true {
showIntro()
} else {
skipIntro()
}
}
func resetControllers() {
setShowIntroFlag()
loadControllers()
}

Dismiss pushed view controller

So I have a view controller which I display as follows:
func showProfileForTrainer(trainer: Trainers) {
let viewPTProfileVC = ViewPTProfileVC()
viewPTProfileVC.trainer = trainer
self.navigationController?.pushViewController(viewPTProfileVC, animated: true)
}
But when trying to dismiss the view, I cannot get it to work. It has a back button in a navigation bar which functions fine, but when trying to dismiss the view via a button for example, it does nothing. I have currently tried:
func handleMessageTrainer() {
dismiss(animated: true) {
print(1)
self.tabBarVC?.showChatLogForTrainer(trainer: self.trainer!)
}
self.dismiss(animated: true) {
print(2)
self.tabBarVC?.showChatLogForTrainer(trainer: self.trainer!)
}
navigationController?.dismiss(animated: true, completion: {
print(3)
self.tabBarVC?.showChatLogForTrainer(trainer: self.trainer!)
})
self.navigationController?.dismiss(animated: true, completion: {
print(4)
self.tabBarVC?.showChatLogForTrainer(trainer: self.trainer!)
})
print(5)
}
As you can see I have tried varying ways and none work, and the console just outputs 5.
Frustratingly, elsewhere in my app I presented a view in the same way as shown at the beginning and it dismissed fine using dismiss(animated: true) { ... }
Any idea why it won't work here?
You must pop the view controller from the corresponding navigation controller:
self.navigationController?.popViewController(animated: true)
If you are using pushviewcontroller method then to dismiss you have to use popviewcontroller method.
Try this:
self.navigationController?.popViewController(animated: true)

Resources