CABasicAnimation stops when relaunching the app

2019-06-25 23:14发布

问题:

I am running into a problem where a restart of my iPhone app causes animations to stop. More specifically, I have the following animation set and running:

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
animation.duration = 1.0;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.repeatCount = 1e100f; // Infinite
animation.autoreverses = YES;
animation.fromValue = animationStartPath;
animation.toValue = animationFinishPath;
[view.layer addAnimation:animation forKey:@"animatePath"];

When I press the home key (iOS 4 so it is still 'running' in the background) and then relaunch the program, the animation has stopped. Is there any way to prevent this or easily restart them?

回答1:

There are two methods in your app delegate where you can pass down information to your view controller that is performing the animation.

- (void)applicationWillResignActive:(UIApplication *)application
{
  // Make note of whether or not the animation is running.
  // Using NSUserDefaults is probably the simplest
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
  // Check your user default setting to see if the animation
  // was running when the app resigned active and then restart it
}

Of course this means you'll need a reference to your view controller that is performing the animation in your app delegate, or you could use notifications to pass the notification along. Anyhow, the bottom line is you'll have to watch for the app becoming active again and restart the animation.