UIImage animations don't work in a view pushed without animation - iphone

I've got a view controller whose view contains a UIImageView that does animation:
//AnimationViewController::ViewDidLoad event:
var ctlAnimations = new UIImageView();
ctlAnimations.AnimationImages = list.ToArray(); //<--list contains the UIImages
ctlAnimations.AnimationDuration = 1.0 * list.Count;
ctlAnimations.StartAnimating();
this.Add(ctlAnimations);
This works perfectly: when I push AnimationViewController onto the navigation stack, it displays and animates the UIImage.
But now I need to show AnimationViewController with a custom animated transition:
var transition = CATransition.CreateAnimation ();
transition.Duration = 0.3f;
transition.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut);
transition.Type = CATransition.TransitionFade;
this.View.Layer.AddAnimation (transition, "fade");
//viewController is being pushed with animated=false, because we have a custom animation
base.PushViewController (viewController, false);
this.View.Layer.RemoveAnimation("fade");
This also works perfectly, in that the new View transitions into place using the specified custom animation.
But when I push AnimationViewController onto the stack using an animated transition, it displays but the animation doesn't run. Instead, it shows the first frame of the animation (the first image in the list), and doesn't run it.
So, something about the transition is breaking the ability to animate a UIImage in the new view controller, but I simply can't figure out what to do about it.
Update: I've noticed that if I tap the NavigationController's back button, but then move off of the back button and let go (so I don't actually go back), the animation starts playing!

PushViewController works like this: Over the current view controller the next view controller is placed you can say pushed onto the stack. From Apple docs its clear that either you need to push view controllers either with animation or without.
Work around:
Set the frame of the next view controller's view's x position beyond
the screen's right
Suppose width of the screen is 320, then set the x position of next
view as 320.
Add the next view as subview to the existing one.
Now do your custom animation.
Another work around:(a bit more overhead though)
Take a snapshot programmatically of current view.
Add the snapshot image as the initial view of next view controller.
Now push view controller without animation. (User will still see the old view)
In viewDidAppear of new view controller start your custom animation.
[I have to warn you that this method of taking snapshot might give you a small delay in older devices. Newer devices are pretty fast enough you wont see any lag]
Let me know if any issues in case you are implementing any of these solutions.

Try putting the animating bit in ViewDidAppear rather than ViewDidLoad. Also, try using breakpoints and NSLogs to follow what happens after the animation, starting with the ViewDidLoad and ViewDidAppear. Try having the animation repeat forever so you can see if it has ever been animating or not.

I'm very curious what the culprit is here as well. Why is the animation not displaying correctly in some cases?
My theory is that you have placed animation code in viewWillAppear rather than viewDidAppear. Animation code does not run properly when placed in WILL or SHOULD methods.
Can you please post back what caused the issue?

Suspicion #1
I am betting that your code is not being called because it is in ViewDidLoad. I believe you are creating a customized view stack, that means you need to be using the ChildViewController methods from Cocoa.
I am unfamiliar with MonoTouch (I only write pure CocoaTouch), so this might not be 100% correct
I would be consoling out your viewDidLoad and viewDidAppear methods and absolutely make sure they are being called. It is my suspicion that viewDidLoad IS NOT. And this is causing viewDidLoad to not be called on the UIImageView.
In your code you probably need the equivalent of (from objective-c):
[self addChildViewController:viewController];
// OR?
[base addChildViewController:viewController];
This tells the 'parent' viewController that the Child has been made visible, so call the viewDidLoad/Appear and Unload/Disappear methods when appropriate. This might not exist in MonoTouch, or the Push methods might not be fully implemented, so you might need to do some hacky (bad) stuff like manually calling the viewDidLoad method manually.
Suspicion #2
It could also be that your 'list' variable (the one holding the images) is nil. If that happened the animation would not run. OR maybe it has something to do with the duration of your animation, try to set it to whatever would make it repeat forever. Be sure it isn't running REAL FAST somehow and you are just missing it.
begin philosophical musing
Either that or start learning actual Cocoa development :) Not meant as a flame, but definitely meant seriously, you are going to run into problems trying to develop applications through translation layers (custom language-bridges meant to get around writing the base language of a framework/application/platform).
Titanium/MonoTouch/PhoneGap will never produce as robust or high-quality applications as real Objective-C. And besides that, once you learn Cocoa it will change how you write everything else, and I doubt you will want to go back. As the wonderful website of the same name says, 'Cocoa is my girlfriend'

Let me tell the something about UI in IOS. In IOS access to the UI Elements is limited to a single thread.
The single thread would always be the mainThread except in the case when you are running an animation.
Hence when u are performing number of animation at the same instance you have to use
beginAnimation.
setFrame (or) some methods that changes state of UI element.
Repeat step2 for all those objects u are scheduling to animate.
comitAnimations to perform all animations at once. (using comit animations ensure all the animations are performed on same thread)
So, I guess here is what happening in ur case.
Viewcontroller started an animation to push the view controller into stack.
Image view started another animation before finishing first animation.
Look at the links to get a clear idea link1 and link2.
Well Let's get into the solution
Add an ivar and retained property named ctlAnimations to your class
In ViewDidLoad (or) ViewDidAppear
self.ctlAnimations = new UIImageView();
ctlAnimations.image=(UIImage*)[list.toArray() objectAtIndex:0];
this.Add(ctlAnimations);
[self performSelector:#selector(startAnimatingImage) afterDelay:0.1];
Create a private method named startAnimatingImage with below code
self.ctlAnimations.AnimationImages = list.ToArray();
ctlAnimations.AnimationDuration = 1.0 * list.Count;
ctlAnimations.StartAnimating();
On a brief we just shown first image for a moment when the firstanimation is taken place and then we delayed animation start for 1 second so that it performs after first animation and then starts animating the image.
Go ahead and give it a try

There is the concept for the Main thread. So UIAnimation are actually works on Main Thread and at the same time may be this was happen that another task is performing on the same Main Thread.So that was a case like IOS will give preference according to processes id of each process at a time and for the solution you need to make background thread for the same operations.

Well, I never figured out what the problem was here, but it also turned out that there was some sort of memory leak in UIImage such that on some phones my code was crashing.
So I rewrote it to do the animation manually. Now I set a timer and keep a frame index variable, and every time the timer rings I change the image myself. This amounts to the same thing, and it turns out it fixes this problem.

Related

How can I optimize my controllers so they load faster?

Most of the iOS apps I use are very responsive, when I tap on an element it goes to the next view right away. In my app, some of my view controllers take 0.5-1.0 second to load.
My code is all in the viewDidLoad method and I'm pretty sure that's the problem but I can't move anything out since I need every single element that I instantiate.
A solution I thought is to move all the work I do in viewDidLoad in a thread then call the main thread when I'm ready to call addSubview, would that work even if UIKit is not thread safe? Or is there something else I'm missing?
Try to move some code you might have in viewDidLoad to viewdidAppear. viewDidAppear is being called once the view is presented. If you have to make some hard work, do it there and maybe show aa spinner somewhere while you do that.
What are you exactly doing in viewDidLoad? Btw remember that a view is only loaded when you need it, if you want to switch between views faster I can suggest you to create an initializion phase where you call -view on all the view controller you want to show, maybe helped with a spinner or a progress bar. but pay attention this would work only with intensive loading task and not memory consuming tasks. It sounds very strange your request, so is better the you try to explain better why your viewDidLoad is so slow, maybe there is something wrong.
Define your UI elements in Xcode as part of designing the interface. That way, Xcode can compile your storeyboard or xib files into the rapidly loading binary form.

Poor animation performance transitioning to UIViewController (via UINavigationController) and not sure why

I have a simple UIViewController whose view is created via a Nib. Here's the structure of the Nib:
And a screenshot of the layout:
Whatever the previous view (there are 2 possibilities), there is significant stutter/lag when transitioning to this view. Even the keyboard animation is lagged. Also, this is only on an actual device.
I've tried removing the MKMapView to see if that was the case, but it didn't make a difference.
Is the Nib too complex? Should I load everything via code? I'm not sure what it could be, but its really annoying, especially when the rest of the app is super crisp.
As far as code goes, its nothing special: just alloc/init a view, push it onto a UINavigationController, etc. Nothing in the viewWillAppear:/viewWillDisappear:.
Coming from Reddit, where you posted code (probably want to do that here too):
My guess would be the lag is coming from the section from line 44 through 80ish, where you build the overlay. Something in there might be taking longer than you think (Spotpoint unSerialize sounds fishy). You typically want to do as little work as possible in viewDidLoad, since that is called as the UI is transitioning to the new view controller.
Try throwing that code into a GCD queue or running it in the background, and see if that helps the loading stutter.

Are animations automatically removed from layers when switching viewcontrollers?

I've setup a simple CAKeyframeAnimation with infinite repeatcount and added it to a layer. All is fine except that the animation is removed when I switch to another tab (or very likely any other mechanism of changing the active view controller).
Is this documented anywhere, perhaps new in iOS 5, and is there another solution than starting the animation again in viewWillAppear? The timebase is irrelevant in this case, starting the animation from time 0 would be fine.
You should not perform any work with View while it is not on screen, because it's just waste of iPhone resources. Besides your application can get memory warning and view will be unloaded.
IMHO the best approach is to set up graphics in -(void) viewWillAppear and start animations in -(void) viewDidAppear.
P.S. In -(void) viewDidLoad parameters of frame of view are still not valid and if you try to use them, you can get something wrong.

How do I create a reusable Loading Screen?

How do I create a loading screen that can be reused at any given time. I'm aware of the Default.png but I need the flexibility to plug in a loading screen at any point during the application life cycle.
This is what I have thus far.
//inside a method that gets called by a UIButton
LoadingViewController* loadController = [[LoadingViewController alloc] initWithNibName:#"Loading" bundle:nil vertical:NO];
[self.view addSubview: loadController.view];
//some method call that takes a few seconds to execute
[self doSomething];
//This loads some other view, my final view
[self.view addSubview: someOtherView]
but it seems that the loading view is never displayed. Instead the previous view stays there until the "someOtherView" gets added. I put trace logs and the code does seem to get executed, I even replaced [self doSomething] with a sleep(2), but the intermediate loading view is never displayed.
If I remove [self.view addSubview:someOtherView]; then after a few seconds...(after doSomething finishes executing) the load view is displayed since there is no view that is pushed on top of it, however this is obviously not the functionality I want.
Can explain this behavior? Is there something about the rendering cycle that I am misunderstanding because it doesn't seem like the view (on the screen at least) is instantly updated, even though I call a [self.view addSubview: loadController.view];
Would I need to create a separate thread?
In general, for changes in the UI to be made visible to the user, control must return to the main runLoop. You are only returning to the runLoop after taking the loading view down and replacing it with the other view. One strategy for dealing with this is to move the code that does the loading onto another thread. NSOperation and NSOperationQueue can be used for this.
An even simpler approach is to use performSelectorInBackground:withObject to do the processing. Once processing is complete the UI can be updated again to show the data. It is important to remember that the UI updates must be carried out on the main thread. Use performSelectorOnMainThread:withObject:waitUntilDone: to accomplish this from the loading thread.
This sounds like a lot of complication but it is really as simple as breaking your single method up into three separate methods as follows:
Display the loading view and start the background process - this is the button action method.
Do the background loading - called from the button action function with performSelectorInBackground:withObject.
Remove the loading view and update the display with the data - called from the background thread with performSelectorOnMainThread:withObject:waitUntilDone.
I created a subclass of UIView where I initialized how my loading-view should work and look like. (My view appeared and slided in from the bottom with an nice animation).
I then added code that handled whether the loading-view should be visible or not in a subclass of UIViewController.
I then let all my viewcontrollers be an subclass of my new viewcontrollerclass which made it possible for me to do:
[self showloadingMessage:#"loading..."];
in all my viewcontrollers...

Custom view transition in OpenGL ES

I'm trying to create a custom transition, to serve as a replacement for a default transition you would get here, for example:
[self.navigationController pushViewController:someController animated:YES];
I have prepared an OpenGL-based view that performs an effect on some static texture mapped to a plane (let's say it's a copy of the flip effect in Core Animation). What I don't know how to do is:
grab current view content and make a texture out of it (I remember seeing a function that does just that, but can't find it)
how to do the same for the view that is currently offscreen and is going to replace current view
are there some APIs I can hook to in order to make my transition class as native as possible (make it a kind of Core Animation effect)?
Any thoughts or links are greatly appreciated!
UPDATE
Jeffrey Forbes's answer works great as a solution to capture the content of a view.
What I haven't figured out yet is how to capture the content of the view I want to transition to, which should be invisible until the transition is done.
Also, which method should I use to present the OpenGL view?
For demonstration purposes I used pushViewController. That affects the navbar, though, which I actually want to go one item back, with animation, check this vid for explanation:
http://vimeo.com/4649397.
Another option would be to go with presentViewController, but that shows fullscreen.
Do you think maybe creating another window (or view?) could be useful?
While I cannot completely answer your question without doing some more research of my own, I can help a bit:
-In order to get the view of a UINavigationController, you need to take a screenshot. The easiest way to do this is by grabbing it into a UIImage:
UIGraphicsBeginImageContext(self.view.frame.size);
[[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage* test = UIGraphicsGetImageFromCurrentImageContext();
UIImageView* view = [[UIImageView alloc] initWithImage:test];
UIGraphicsEndImageContext();
I am not sure if you can render a GLContext (not familiar on the phone) into a CGImage, but I would do something like that (and init a UIImage from that). I would prerender every frame of the animation you are trying to do and slap it into an UIImageView using the animation stuff provided within. That is, if your animation is simple enough. Otherwise, it might come down to writing your own animation function :-/
I have just put together a transition class to implement your own transition animation in OpenGL ES.
Feel free to read about it here
There are two example transitions in the project, feel free to add you own to it.
I think the function you might be thinking of is http://www.opengl.org/sdk/docs/man/xhtml/glCopyTexImage2D.xml ... you set the viewport to the texture size and then draw as usual, then do glCopyTexImage2D to copy the scene onto a texture.
or you should look into FrameBuffer Objects. The default OpenGL template in XCode uses these. Just generate the example project to see how those work.
I recently write some transitioning animation betweeen view controllers like you. If you want to get any extra info from the invisible view, you can try delaying the transition like this :
- (void)animationFromModalView:(UIView *)modalView toMasterView:(UIView *)masterView
{
[masterView setNeedsLayout];
[masterView layoutIfNeeded];
[self performSelector:#selector(delayAnimationFromModalViewToMasterView) withObject:nil afterDelay:.1f];
}