Initialising a ViewController before Segue - ios

I am performing a segue to a view controller that requires an initialisation process. At present the initialisation happens in ViewDidLoad of the target view controller. However the initialisation is fairly lengthy and I would like to show a spinner while it is happening.
If I create a UIActivityIndicatorView within ViewDidLoad and run the initialisation on another thread, of course ViewDidLoad exits and the rest of the loading process happens - in particular shouldAutorotate is called, and this contains code that assumes the initialisation process has occurred. (Even if it didn't, I do not want to show the target view before it has been initialised.)
The answer seems to be to initialise the target view controller before calling the segue. However I can't do that in prepareForSegue in the calling view controller, for the same reason - it exits and the segue is called before the initialisation has happened.
So I seem to need to instantiate the target controller, initialise it and then perform the segue with the initialised controller as the destination. My problem is that I don't know how to do that. The only possible way I have come across is to subclass UIStoryboardSegue and put the initialisation in the init for the subclass. Then I presume I call
UIStoryboardSegue * segue = [[SubclassedSegue alloc]initWithIdentifier:#"??what should this be??" source:self destination:targetViewContoller];
[segue perform]; // which just calls [super perform];
from the source view controller. Is this correct? Can anyone please show me some example code that uses this process - or preferably a simpler way that I haven't thought of? I can't help thinking there must be an easier way to show a spinner.
Thank you for your help.

Segues should be subclassed only when you need to show custom animation/transition during the segue.
In usual scenario, you would want to do this:
__ block Destination *destinationVC = [self.storyboard instantiateViewControllerWithIdentifier:#"destination "];
//START BUSY CURSOR HERE
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
// init whatever you want for destinationVC HERE.
dispatch_async(dispatch_get_main_queue(),
^{
//STOP BUSY CURSOR
//PERFORM UI UPDATE HERE
[self presentViewController:destinationVC animated:YES completion:nil];
});

just have the destinationViewController always add an activityIndicator and in viewWillAppear .. just hide it if you don't need it anymore
Alternatively pass a flag to the destinationViewController in prepareForSegue.
You shouldn't need to subclass UISegue!

Related

Pushing a new VC into the navigationController seems to have no effect

This problem sounds quite basic but I don’t understand what I am overlooking.
I am trying to push a new view controller into a navigation controller, however the topViewController remains unaffected.
#import "TNPViewController.h"
#interface TNCViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
#implementation TNCViewController
-(void)userDidSelectNewsNotification:(NSNotification*)note
{
TNPViewController *nextViewController = [[TNPViewController alloc] init];
[[self navigationController] pushViewController:nextViewController animated:YES];
UIViewController *test = [[self navigationController] topViewController];
}
The test shows an instance of TNCViewController instead of TNPViewController. How is this possible?
UPDATE
Thanks for everyone's participation. The method name indicating notifications is a red herring. I found the problem, as Stuart had mentioned previously but deleted later on. (As I have high reputation score, I still can see his deleted post).
My initial unit test was this:
-(void)testSelectingNewsPushesNewViewController
{
[viewController userDidSelectNewsNotification:nil];
UIViewController *currentTopVC = navController.topViewController;
XCTAssertFalse([currentTopVC isEqual:viewController], #"New viewcontroller should be pushed onto the stack.");
XCTAssertTrue([currentTopVC isKindOfClass:[TNPViewController class]], #"New vc should be a TNPViewController");
}
And it failed. Then I set a breakpoint and tried the test instance above and it still was showing the wrong topviewcontroller.
At least the unit test works if I change
[[self navigationController] pushViewController:nextViewController animated:YES];
to
[[self navigationController] pushViewController:nextViewController animated:NO];
A better solution is to use an ANIMATED constant for unit tests to disable the animations.
This doesn't really answer your question about why your navigationController is not pushing your VC. But it is a suggestion about another possible approach.
You could instead add a new VC on the Storyboard and simply activate the segue when the userDidSelectNewsNotification method is activated. Then change the information accordingly to the event in the VC, specially since you are initializing it every time anyway.
This is something of a stab in the dark, but the issue is hard to diagnose without more information.
I see you're trying to push the new view controller in response to a notification. Are you sure this notification is being handled on the main thread? UI methods such as pushing new view controllers will fail (or at least behave unpredictably) when not performed on the main thread. This may also go some way to explaining the odd behaviour of topViewController returning an unexpected view controller instance.*
Ideally, you should guarantee these notifications are posted on the main thread, so they will be received on that same thread. If you cannot guarantee this (for example if you're not responsible for posting the notifications elsewhere in your code), then you should dispatch any UI-related code to the main thread:
- (void)userDidSelectNewsNotification:(NSNotification *)note
{
dispatch_async(dispatch_get_main_queue(), ^{
TNPViewController *nextViewController = [[TNPViewController alloc] initWithNibName:#"TNPViewController" bundle:nil];
[self.navigationController pushViewController:nextViewController animated:YES];
});
}
Also, it appears you are not initialising TNPViewController using the designated initialiser (unless in your subclass you are overriding init and calling through to initWithNibName:bundle: from there?). I wouldn't expect this to cause the transition to fail entirely, but may result in your view controller not being properly initialised.
In general, you might be better creating your view controllers in a storyboard and using segues to perform your navigation transitions, as #Joze suggests in his answer. You can still initiate these storyboard segues in code (e.g. in response to your notification) with performSegueWithIdentifier:, but again, be sure to do so on the main thread. See Using View Controllers in Your App for more details on this approach.
*I originally wrote an answer trying to explain the unexpected topViewController value as being a result of deferred animated transitions. While it is true that animated transitions are deferred, this does not prevent topViewController from being set to the new view controller immediately.

How to wait for a UIViewController to be completely initialized?

I have a custom segue type (overriding init and perform methods of UIStoryboardSegue) and in init method I instantiate the destination view controller(VC). In prepareForSegue method of source VC I call a method of the destination VC that tries to reload the tableView of the destination VC. The problem is that the table view is not always initialized and I SOMETIMES get a nil de-reference error when I call the reloaddata of the tableview.
The question is that how can I wait till the VC is fully initialized and do not get this error?
I am using swift and would appreciate if you write any sample code for the answer in swift.
just make a call on the viewController's view to force its load.
[viewController view]; //will force a loadView if necessary
///then do what you're trying to do..
I think that the best approach in this case is to add a flag property in the destination VC, something like:
var forceReload: Bool
that you set from prepareForSegue in the source VC. This way, you can choose where to actually perform the data reload from the destination VC (for example, in viewDidLoad or viewWillAppear) by simply checking the value of that flag - of course if the flag is true, don't remember to reset it.
If you also need to pass data from the source to the destination VC, use one or more properties declared in the destination and set from the source.

Programmatically Selecting a TabBarController View?

In order to get my custom menu up and running, I've ended up using a UITabBarController and need to change the view displayed programmatically, vs the standard tabbed menu on screen.
Everything is working as expected except on thing. I am attempting to use:
[self setSelectedIndex:index];
This code is inside my UITabBarController subclass in a custom delegate method. (This is so I can programmatically adjust the view when interacting with my menu). However, while this code is called, it doesn't do anything?
Does it HAVE to be called from one of the tabbed views? I was hoping to run it from inside the TabBarController to avoid repeating the code in each tabbed sub controller.
UPDATE:
Just found that using [self setSelectedIndex:index]; works fine in viewDidLoad. But when it is called inside the delegate method, it doesn't change view. It is using the right index number and getting called, but not doing anything from that method.
Also, it seems the tab controller is a different object when I log self in viewDidLoad vs my delegate method. So why would I be loosing the reference to the original controller?
It's just a UITabBarController in a container in another view controller.
Delegate Code:
#Interface
#protocol SLMenuDelegate <NSObject>
#required -(void)menuDidChangeViewToIndex:(NSInteger)index;
#end
#property (nonatomic, assign) id<SLMenuDelegate>menuDelegate;
#Implementation
#synthesize menuDelegate;
self.menuDelegate = [self.storyboard instantiateViewControllerWithIdentifier:#"TabBarViewController"];
[menuDelegate menuDidChangeViewToIndex:[self.menuItemButtons indexOfObject:sender]];
UITabBarController
-(void)menuDidChangeViewToIndex:(NSInteger)index
{
[self setSelectedIndex:index];
}
Setting breakpoints and running NSLogs and there is no question that the method gets called and all code runs.
Try using delayed performance:
dispatch_async(dispatch_get_main_queue(), ^{
[self setSelectedIndex:index];
});
I didn't manage to find a solution to the exact issue, but I found an equally good way of resolving my issue simply.
I stopped using a delegate to send my button tap message and change the view. Instead I did the following:
SLTabBarViewController *tabBar = [self.childViewControllers objectAtIndex:0];
[tabBar setSelectedIndex:[self.menuItemButtons indexOfObject:sender]];
This gets the embedded tab bar controller and I simply directly change the view from the original view controller from which the button tap comes from.
It may not be an intelligent solution, but its a simple and functional one which doesn't create any problems.

Custom UIStoryboardSegue using segueWithIdentifier:source:destination:performHandler:

I am trying to use a custom UIStoryboardSegue to implement a transition between two view controllers. I can do this by subclassing UIStoryboardSegue, and then setting this class in IB. However, I was looking at the docs which say:
If your segue does not need to store additional information or provide anything other than a perform method, consider using the segueWithIdentifier:source:destination:performHandler: method instead.
Implying that you don't need to create the custom subclass, just use the custom performHandler.
I am confused as to where this code should go, and how I go about using it. Do I create the segue as normal in IB and then override that before it is fired (maybe in shouldPerformSegue: or similar). Elsewhere in apple's documentation it says:
Your app never creates segue objects directly; they are always created on your behalf by iOS when a segue is triggered
So I don't quite understand why they are then saying to instantiate a segue using a class creator method.
The point of segueWithIdentifier:source:destination:performHandler:
Provide an alternative to UIViewController performSegueWithIdentifier:sender in cases where you also want to create a custom transition, without creating a segue subclass.
Vend a segue that can be used as the return for segueForUnwindingToViewController:fromViewController:identifier
As noted above, this approach is only viable for segues which you would call manually -- i.e. not for segues that would otherwise be triggered via IB triggers.
So, for example, if you have a segue that needs to be triggered after a certain timeout period (such as a custom lock-screen), you could use segueWithIdentifier:source:destination:performHandler: to handle the custom transition.
-(void)appTimeoutLockScreen
{
UIStoryboardSegue *segue =
[UIStoryboardSegue segueWithIdentifier:#"LockScreenSegue"
source:sourceVC
destination:destinationVC
performHandler:^{
// transition code that would
// normally go in the perform method
}];
// Dev is responsible for calling prepareForSegue and perform.
// Note, the order of calls for an IB triggered segue as well as
// a performSegueWithIdentifier segue is perform first, then
// prepareForSegue:sender. Manual segues need to inverse the call
// in order to ensure VC setup is finished before transition.
[self prepareForSegue:segue sender:self];
[segue perform];
}
Another practical use for the method is unwinding segues. Using a similar scenario
to the previous example, we could use it to return a segue to transition from a lock screen back to the previous viewController:
-(UIStoryboardSegue *)segueForUnwindingToViewController:(UIViewController*)toVC
fromViewController:(UIViewController *)fmVC
identifier:(NSString *)identifier
{
UIStoryboardSegue *segue =
[UIStoryboardSegue segueWithIdentifier:#"FromLockScreenSegue"
source:fmVC
destination:toVC
performHandler:^{
// transition code
}];
return segue;
}

Drawing in segue vs writing code to transition views - why does data sometimes not transfer?

Let's say I have a UILabel on ViewControllerA and and UITextField on ViewControllerB. I want to go to ViewControllerB and input text then press a button to go back to ViewControllerA. The UILabel should now read whatever was typed in the UITextField.
I was able to accomplish the above by using NSUserDefaults and also using delegation. I am using Storyboards to do this. My question is about the segues used in the storyboards.
It seems when using delegation I must go to and from the storyboard with code and not visually connect the view controllers with a segue in order for the data to transfer. Here is the code when I press a button on my ViewController A:
- (IBAction)pressFirstButton:(id)sender {
UIStoryboard* sb = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
RBViewController2 *vc2 = [sb instantiateViewControllerWithIdentifier:#"ViewController2"];
[vc2 setDelegate:self];
[self presentViewController:vc2 animated:YES completion:NULL];
}
when passing the data back from ViewControllerB to ViewControllerA I do this:
- (IBAction)buttonSegueBackTo1:(id)sender {
NSString *sendThis = self.textFieldVC2.text;
[self.delegate passTextFieldInput:sendThis];
[self dismissViewControllerAnimated:YES completion:NULL];
}
No segue has been drawn between the view controllers and everything works fine. If I don't write this same code, and draw in a segue, the data won't pass backwards. However when I try passing data like this using NSUserDefaults I don't have to write the code to go to and from the view controllers. Instead I can simply connect the view controllers with a drawn segue. The weird thing is, if I'm trying to pass the data in using NSUserDefaults when manually coding the view controllers (an not drawing the segue) the data doesn't transfer.
I'm thinking maybe instead of writing the code in the -(IBAction) pressFirstButton:(id) sender method, I should be putting the code in the prepareForSegue method.
My question is why do drawn segues sometime cause data to be lost? Must all delegation be done without drawn segues? If NSUserDefaults require segues to transfer properly and delegation require code to transfer properly then if I have a view that requires both, it seems that NSUserDefaults will trump the delegation b/c the manual segue being used "resets" the view and only the NSUserDefaults data remains.
Normal segues (any other than unwind segues) ALWAYS create new view controllers. So, if you're using anything other than an unwind segue to go back to A, you're really not "going back", you're creating a new ViewControllerA. Unwind segues aren't normally used in a case like you're presenting, just going back one controller, but you could.
This situation also isn't a good place to use user defaults. The Apple recommended way, is to use delegation, like you do in the code your question. The way you show, is probably the best way to do it, rather than using a segue to go back. You certainly could use a segue to go forward though, and in that case you would implement prepareForSegue: so you can set yourself as the delegate and/or pass any data forward.
Your question is a little dense to parse but I think you are asking if there is a way to get pass data through segues. The answer is yes, and much better than the workarounds you are trying.
In your button you would call:
[self performSegueWithIdentifier:#"scrollerSegue" sender:self];
This will trigger the method below and it is here that you can set the data on the destination viewController. You can set abstract properties on the destination viewController but you can't populate an UIKit elements (labels, imageViews, etc.) because they don't exist yet. Instead set properties and then in viewWillAppear in the destination viewController, do the set up as needed. (alternatively, instead of passing data, you could just set the delegate and then call methods on the delegate to get the data as needed).
For getting data back, using the delegate and calling methods on it seems to be the Apple recommended way of doing things.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"scrollerSegue"])
{
ScrollViewController * target = segue.destinationViewController;
target.assetsArray = self.assetsArray;
target.delegate = self;
}
}

Resources