I am having a weird issue where my app crashes when I am trying to push a new view controller. I have set up a swipe gesture and want to segue to another view controller when a swipe is detected. When I run these 2 lines of code ...
let viewController:ViewController = ViewController()
self.navigationController?.pushViewController(viewController, animated: true)
The app crashes not specifically on either of those lines of code but rather in my ViewController class when in my viewDidLoad method I run this piece of code...
imageView.layer.masksToBounds = true
If I comment that out it crashes when I set the auto-correction type of my textField. What am I doing wrong?
First place I look when the view immediately crashes is in the Outlets for that ViewController in InterfaceBuilder. I look for anything that shows up with an exclamation mark. That usually means I renamed an outlet or broke a connection somehow. Delete anything broken by pressing the little x by the item that's messed up. I'll attach a photo so you can see.
It seems you're loading a ViewController that exists in storyboard with
let viewController:ViewController = ViewController()
which will result in nil outlets , so you have to use
let viewController = storyboard.instantiateViewController(withIdentifier: "VCID") as! ViewController
and give that vc a storyboard identifier like VCID
I think I have solved the issue but it has a weird side effect. Instead of using the line of code in #Sh_Khan's answer, I used ...
let viewController = nav?.storyboard!.instantiateViewController(withIdentifier: "mainVC") as! ViewController
The variable nav is equal to the navigation controller of the current view-controller. This seems to work without any hiccups but for some reason the back button does not disappear from the navigation controller after the segue is preformed. Does anybody know a solution to this, if so leave a comment and I will update my answer.
EDIT:
Another issue is that it wipes everything changed on that ViewController by the user clear. Is there another way to instantiate a ViewController without clearing it?
Follow what #Sh_Khan has said and in addition to that make sure that the view that you are making the push segue from is embedded in a Navigation controller.
here is my scenario case.
Initially for going to this VC without loading is hidden.when I click to first view controllers button it goes to second view controller.When I click button from secondVC it come back to first one and for going to this VC without loading button is now visible.Now when I click for going to this VC without loading I want to show my second view controller without reload because my previous loaded data for second view controller is needed.So how can I do that?
the actual scenario of my app look like this.My first VC
and the second one.
It's a picture of sound cloud but the case is same.
First possible solution,
Add SecondViewController as child view controller of FirstViewController using container view in Storyboard.
Every time you want to remove SecondViewController just hide/remove it with custom animation block.
Keep the reference of SecondViewController in FirstViewController
Second possible solution,
Create shared data object.
Then you can use that shared data object in any view controller, regardless of saving the state of any view controller.
I would create an object where i put the data und pass this from ViewController to ViewController by properties. Maybe this is to simple but it should work.
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.
I have a function in my AppDelegate which is similar to, DidReceiveRemoteNotification, and upon receiving a message appends a message to an array and then attempts to reload a tableview.
My app consists of just one Viewcontroller and one AppDelegate.
My code looks like this:
var myCustomViewController: ViewController = ViewController(nibName: nil, bundle: nil)
println("******didReceiveMessage*****")
myCustomViewController.messages.append(message.data.message as! String)
println(myCustomViewController.messages)
myCustomViewController.MessageTableView.reloadData()
whenever I try to call a reload function my app crashes however. Is there a way to reload my tableView from my appDelegate function?
Your view isn't loaded yet, so the table view doesn't exist yet, hence it is nil.
It isn't clear whether you're using the correct view controller, because you're creating a new one. Either call view on it to create the view (and subviews) or change the reference to the real existing view controller.
Most likely you should be accessing the root view controller of the app delegates window.
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.