ViewControllers are not destructing - ios

I've got a serious problem with my iOS app.
I have a login logic in my application. When logging in and then logging out, some view controllers are not destructing. This causes some issues, for example, some events that I emit using NSNotifcationCenter are emitted few times. These issues are avoidable, but I really want a solution to avoid some view controllers to stay open in the background without me controlling it.
The way control the login logic is as follows:
In the app delegate start function, if the user is already logged in, I set the root view controller to the main usable view controller. Therefore, I'm not doing anything and the root view controller is set to the login view controller navigation controller through the storyboard.
When the user logs off, I use a modal segue to transition the view controller back to the login view controller navigation controller.
As you may understand I'm using storyboards, swift and the newest iOS.
My logout code is segue that take me to the LoginViewControler:
self.performSegueWithIdentifier("Logout", sender: self)
My app delegate code:
if (userDefaults.valueForKey("uid") != nil) {
let tabBarView = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("TabBarViewController") as! TabBarViewController
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window?.rootViewController = tabBarView
}
What am I doing wrong?
I would appreciate help :)
EDIT
I even tried just setting the root view controller in the logout action and that didn’t help either. How’s that even possible?
This is how I do the logout now:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let newRootViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginNavigationController") as! UINavigationController
appDelegate.window!.rootViewController = newRootViewController

Adam H. is right. If that doesn't work, then check for IBOutlets and delegates that have strong relationships, and change them to weak relationships. i.e.
#IBOutlet weak var collectionView: UICollectionView!
Without the weak keyword the view controller will never be disposed.
Depending on how your project is setup, if you are using a navigation controller (which I recommend) every time someone logs out you would put
dispatch_async(dispatch_get_main_queue()) {
self.navigationController.popToRootViewControllerAnimated(true)
}
That will pop everything off the navigation stack, which will dispose of all view controllers (unless you have strong relations, then they won't be disposed)

No matter how you choose to manage your trasitions , don't forget to add/ remove the observer whenever the view controller apear/disappear.

If the logged in screen presents the login screen and the login screen presents the logged in screen then you will have a cycle that keeps piling on new view controllers. To solve this, one must not present the other, but unwind to it. Another possibility is to hold instances of each as singletons and only present those.

I implemented something like that not long ago and to me it seems you're abusing the UINavigationController life cycle.
After reading your question twice, if I understand it correctly, it seems you're initializing your login view controller as a UINavigationController which stacks-up view controllers. Once user logs out, you're keeping the stack, adding more ViewControllers to the stack using the performSegue.
You can avoid it by using two different scenes -
1) Login View Controller which stands by it self.
2) Main flow of your app - can start with UITabController/ UINavigationController, both or whatever.
In AppDelegate you check -
If user is logged in - do your logics and set the app rootVC to the main flow vc.
Otherwise you set the loginVC (UIViewController) to be the root.
This also allows you to pop the login VC anywhere in the main flow, when needed, without interfering with the main flow.
In your case the loginVC is always UINavigationController's root so you must popToRootVC every time you wish to see it or performSegue to it which is worse because then you create another instance of a UINavigationController and resources never get deallocated.
Obviously in programming, in most cases, there are many solutions to one problem. I'm sure your problem can be solved using your flow. I just think it's bad experience to stack a loginVC over a navigation controller.

Part of the problem is that setting a new rootViewController on the UIWindow doesn't remove the view hierarchy from the old root view controller. That leaves all sorts of strong references hanging around, and if you use Xcode's view debugging, you can see that the the old view hierarchy is still sitting there, behind the new rootViewController's view hierarchy.
Something like this should fix the problem for you and allow your view controllers to deinit:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let newRootViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginNavigationController") as! UINavigationController
appDelegate.window??.rootViewController?.view.removeFromSuperview()
appDelegate.window??.rootViewController?.dismissViewControllerAnimated(false, completion: nil)
appDelegate.window??.rootViewController = newRootViewController

get rid of ARC file by file in build settings or wholesale
per project (it seems that you can have non ARC project but have weak references
while at it: not sporting I suppose but you can have both).
Then override retain and release in the problematic view controller
and see who hold the extra reference by breaking in the overriden
retain and release. It should be an eduficational experience.
The lazy approach is to kill ARC just for the VC in question.
I'd be curious to see how this works for VCs written in swift ;-)
Me thinks it's yet another reason to stay in objc domicile a while longer
until/if swift compiler and runtime solidifies (if ever).
Hope this helps anyone.
PS: It takes forever to compile some swift file in my project and I have NO
idea which swift file is causing this. Duh.

As yet indicated there aren't a lot informations for provide correctly the solution to your question.
I can suggest you to change your approach. I made a similar workflow using a UINavigationController (navigationController) launched from AppDelegate, inside of if we are logged in I put as ViewControllers :
(where self is navigationController and rootViewController is another UINavigationController)
self.setViewControllers[loginViewController, rootViewController]
If your are not logged in you put only loginViewController:
self.setViewControllers[loginViewController]
in this case you can put the rootViewController where the user is logged in.
This is my 2cent.

I like having a root VC which is just blank. When the app starts, root VC immediately displays login VC as a child VC of root VC. When the user successfully authenticates, the login VC notifies root VC, which then adds main VC as a child of root VC, transitions (with a nice animation) from login VC to main VC (using [self transitionFromViewController: toViewController: duration: options: animations: completion:]), and then removes login VC as a child and discards it. On logout, main VC notifies root VC which then does the same thing in reverse. So most of the time you only have either login VC or main VC instantiated; the only time they are both instantiated is during the transition.
I find segues are useful for building quick prototypes, but for production apps I prefer not to use them.

I Guess the ViewControllers Stack of you will go like this:
- 1st launch: LoginVC
- After login: LoginVC - TabarVC
- Click Logout: LoginVC - TabarVC - LoginVC
....
So your below code should work:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let newRootViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginNavigationController") as! UINavigationController
appDelegate.window!.rootViewController = newRootViewController
but it's not:(. In my opinion, You should always let the tabarVC rootViewController. And check in TabarVC, if user is not loged-in or user pressed logout, Present loginVC and dismiss it instead of performSegue.

You must remove your :
self.performSegueWithIdentifier("Logout", sender: self)
Instead of it, you can overriding this segue method, this is enough:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
userDefaults.removeObjectForKey("uid")
if segue.identifier == "Logout" {
let newRootViewController = segue.destinationViewController
// newRootViewController is optional in case you want to pass vars
// do whatever you want with your newRootViewController
}
}
About your NSNotification there are two methods to remove it:
NSNotificationCenter.defaultCenter().removeObserver(self, name: "NotificationIdentifier", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self) // Remove from all notifications being observed
In Swift, you can put the removeObservers in the new and special deinit method.

Related

EXC_BAD_ACCESS in UISplitViewController after unwind segue, then returning

This is an application who interface consists of a tab controller (which has the rest of the interfaces residing in tabs), then two UISplitViewControllers with tables in them, and lastly a simple UIView with a button that allows the user to logout. The logout is implemented with an unwind segue back to the initial view controller (which is a login screen), and setting the root view controller of the app to a freshly instantiated version of the initial view controller (the login interface). After using this logout, then logging back in, the application immediately crashes with an EXC_BAD_ACCESS exception.
I have tried multiple different ways of implementing the behavior of the logout button (to segue back to the login screen) but every attempt has failed with the same results.
By following the stack trace, I was able to determine that the crash is occurring in the setCollapsedState method of the UISplitViewController. This is not a custom implementation of a split view controller, just the default one.
In case this is relevant, I am setting one of the child view controllers of the parent view controller as the delegate, however when I tried changing this and not setting the delegate, nothing improved.
I am not sure what other information I can provide, other than this code snippet of the logout button. If there's any other information that I can supply, please let me know and I will post edits.
#IBAction func signoutButtonPressed(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.signOut()
var rootVC = appDelegate.window?.rootViewController
rootVC?.removeFromParentViewController()
rootVC = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
appDelegate.window!.rootViewController = rootVC
}

Proper Login Flow and TabBar VC

I am having a few issues accessing the tab bar from the App Delegate to setup the Home Screen Quick Actions. Here is the line of code that I am using to access the tab bar. It is returning false.
guard let tabBarController = self.window?.rootViewController as? UITabBarController else {return false}
My tab bar is not my initial VC when the app launches. I have a loading screen during which we authenticate the user token and then it goes to either the login screen or the tab bar controller (which is also the main part of the app) depending on whether the token gets authenticated.
What is best practice for setting up an app with a login screen? The way we are doing it now works fine but I can change it if there is a better way. We are also using Branch for deep linking.
This is a opinion based question and might exist multiple answer to it each of which might be suitable for some specific scenario.
Approach 1 :
This is my personal Favorite does not mean that this is the only proper way of doing it. I prefer replacing the application's rootView Controller either with LoginVC or TabBarVC based on wether the token is valid or not. There are multiple answers in SO explaining how can u replace the application's rootVC with proper animation. Pasting the same code would be redundant here.
Why I use this approach?
Keeps my applications navigation controller stack clean and I don't keep any additional VC's in memory than whats actually required.
Approach 2 :
This is what many people use for the simplest reason that its simple to use but I personally doesn't prefer it. Modally present either Login VC or Tab bar (both of them might be embedded with UINavigationController obviously and you modally present their NavController's which obviously loads its embedded view controller).
Pros:
Easy to code.
You can always be sure that app's rootVC is always fixed and it has presented either LoginVC or TabBarVC. So parsing and accessing the VC's becomes fairly simple.
Cons:
The Landing VC which modally presents unnecessarily remains in Applications Navigation stack through out the apps life cycle. I clearly don't favor this.
EDIT :
As OP has clearly mentioned that he is using approach 2 and wants to know how to access specific VC in tab bars selected index am updating the code show the same.
Code is not intended for Copy paste, code might contain syntactic error. Code provided below is only intended for providing the idea.
Assuming your LandVC does not have UINavigationController embedded to it.
if let landVC = UIApplication.shared.keyWindow?.rootViewController {
if let presentedVC = landVC.presentedViewController {
if presentedVC is LoginVC {
//this is login VC
}
else if presentedVC is UITabBarController {
let currentlySelectedVC = (presentedVC as! UITabBarController).viewControllers?[(presentedVC as! UITabBarController).selectedIndex]
//now check what type VC it is and use it accordingly
}
}
}

How to pop from 3rd ViewController to the initial ViewController without NavigationControllers?

I know this is probably an easy task but I can't get my head around how to solve it. I'm not using a NavigationController by the way. Basically I have 3 view controllers in my app:
-LoginVC (this has a register button. when tapped, it goes to the SignupVC)
-SignupVC (if user signs up, it will push to the MainAppVC)
-MainAppVC (has a logout button)
For the transitions, I use the method: present(viewController, animated:, completion:)
When the user logs in via the LoginVC, he'll be presented the MainAppVC as expected. When he logs out, I'll dismiss the current VC (which is the MainAppVC) to send him back to the LoginVC.
Now here is the case where I have questions about. When the user does not have an account and signs up, this is the VCs he will pass through (LoginVC > SignupVC > MainAppVC). Once he registers successfully, he'll be presented the MainAppVC. Now once he logs out, he'll be transitioned from the MainAppVC to the SignupVC because I used the same dismiss method.
What I want to do is to send the user back to the LoginVC from the MainAppVC. How do I accomplish that without using a navigation controller in my project? How do popular apps (Facebook, Twitter, Instagram, etc) handle this in their apps?
One way I can think of is to perform a segue from 3rd to 1st VC but I think that's a dirty way since it just adds to the stack, instead of popping it off which is a potential issue.
There are three solutions.
1.Use window root view controller.Set root view controller between login and main view controller.
let loginSb = UIStoryboard(name: "Login", bundle: nil)
let loginVc = loginSb.instantiateInitialViewController()
window!.rootViewController = loginVc
2.Dismiss the sign up view controller the first time you present main view controller.And present the main view controller from login view controller.
3.Try to dismiss the sign up view controller in the completion block when you dismiss the main view controller.
I think the first one is best.
If are forced to NOT use a rootViewController (with UINavigationController), you should check in MainAppVC which one is the previous VC (Pseudocode in the example) and do:
Note: Swift 3 Code.
// If previous VC is LoginVC
dismiss(animated: true)
// else if previous VC is SignupVC
// here's what you want
presentingViewController?.presentingViewController?.dismiss(animated: true)
Hope that helped.
Another option is to use unwind segues.
In the ViewController that you want to go back to, implement a method as follows
#IBAction func unwindToLogin(segue: UIStoryboardSegue) {
}
Then in Storyboard, from the last ViewController right click and drag from the button (for example) to Exit and choose unwindToLoginWithSegue.
Note that you can also do this programatically. Here is a good tutorial.
Best approach is :
Dismiss SignUpVC once User Register successfully, Then from LoginVC present MainVC.
In SignupVC :
self.dismissViewControllerAnimated(true, completion: {
self.LoginVC!.present(MainVC, animated: true, completion:nil)
})
This approach is used mostly.

define specific TabBarController that isn´t the initial VC in AppDelegate - swift

In my App there is a TabBarController that ins´t the initial VC.
I wanted to save the new tab order when the user didEndCustomizingViewControllers.
I found a recently asked question: How to: Save order of tabs when customizing tabs in UITabBarController
I used the code of Rickard Elimää which defines the TabBarController as the initial Controller in AppDelegate :
let tabBar: UITabBarController = self.window?.rootViewController as! UITabBarController
For testing whether the code to save the order works I set the TabBarController as the initial Controller and it works.
But the UITabBarController should´t be the initial VC.
So my question is how to define that TabBarController, so that the code works.
Thanks for any help
I found the best way to do this is to implement UIViewControllerTransitionDelegate. This will handle animation as well as passing the rootViewController. It's a tad more complicated than just passing the rootViewController (as I originally had done), but it was worth the time to switch to this in the long run.
Apple Documentation.
www.raywenderlich.com (an implementation example)

How to initiate a viewcontroller without presenting it?

I have a tab bar controller and a few other viewcontrollers outside the tab bar controller. I have this viewcontroller called "X" which is a part of the tab bar controller. I have another viewcontroller called "Y" which is not a part of the tab bar controller. Now i want to initiate X when im inside Y upon tapping a button without actually presenting it. I want X to become active and fire its viewdidload so that i can access X whenever i chose to do so. Is this possible. Im sorry if im not clear in explaining my quiestion. let me know if you need any other additional information.
Old question at this point, but I was looking for an answer myself just yesterday and managed to get it figured out.
Instantiate the ViewController, then call loadViewIfNeeded().
Example:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let exampleVC = storyboard.instantiateViewController(withIdentifier: "ExampleViewController") as! ExampleViewController
exampleVC.loadViewIfNeeded()
If you want, you can then check if the view is loaded with:
exampleVC.isViewLoaded
The ViewController is now all set up and ready for display when you decide to present it.
I want X to become active and fire its viewdidload so that i can access X whenever i chose to do so.
UIViewController uses lazy loading for the view property. You can just call:
[myViewController view];
This will trigger the loadView and/or viewDidLoad methods, if implemented.
However, you may wish to consider moving the relevant logic from viewDidLoad to init (or initWithCoder: if using a storyboard/xib). This way you won't have to call -view.
If I understand right, you want X to be initialised. So you can perform all you initialisation actions on your init constructor. viewDidLoad will only be called by the framework when you perform some presentation, either by pushViewController or addSubview. The reason for that is that because the framework wants to avoid getting instances of views on the memory without being used. So you can initialise all you want from your controllers but the views won't be loaded.

Resources