Search code examples
iphonecocoa-touchcore-animationmultitasking

Why does my indefinite UIView animation stop when my application goes to the background?


I am using the following code for animating a UIView indefinitely:

#define DEFAULT_ANIM_SPPED 0.6
#define INFINATE_VALUE 1e100f

[UIView beginAnimations:nil context:nil];
[UIView setAnimationRepeatAutoreverses:YES];
[UIView setAnimationRepeatCount:INFINATE_VALUE];
[UIView setAnimationDuration:DEFAULT_ANIM_SPPED];
CGRect tempFrame=myView.frame;
tempFrame.origin.y -= 30;
myView.frame=tempFrame;
[UIView commitAnimations];

If my application goes to the background, and then I return to it, all animations like this are now halted. Why would this be happening?


Solution

  • Usually your application's execution is entirely suspended when it goes to the background. Even if your application remains active (for location tracking, VoIP, or some other reason), anything that draws to the screen will be halted when your application moves to the background state:

    Avoid updating your windows and views. While in the background, your application’s windows and views are not visible, so you should not try to update them. Although creating and manipulating window and view objects in the background does not cause your application to be terminated, this work should be postponed until your application moves to the foreground.

    In fact, if you try to draw to an OpenGL ES context in the background, your application will immediately crash:

    Do not make any OpenGL ES calls from your code. You must not create an EAGLContext object or issue any OpenGL ES drawing commands of any kind while running in the background. Using these calls causes your application to be terminated immediately.

    Generally, the recommendation is to pause any animations on the movement of your application to the background, and then to resume those once your application is in the foreground. This can be handled in the -applicationDidEnterBackground: and -applicationWillEnterForeground: delegate methods, or by listening to the UIApplicationDidEnterBackgroundNotification and UIApplicationWillEnterForegroundNotification notifications.