pausing and resuming core animation when app enters and exits background
I have a simple CABasicAnimation wired up as an infinite animation (I have a wheel that I keep rotating forever). Here is the method where I setup that explicit animation:
-(void)perform360rotation:(UIImageView*) imageView {
CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
// to rotate around a specific axis, specify it in the KeyPath parameter like below
//CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation.x"];
[anim setDuration:self.speed]; // Animation duration
[anim setAutoreverses:NO];
[anim setRepeatCount:HUGE_VALF]; // Perfrom animation large number of times
[anim setFromValue:[NSNumber numberWithDouble:0.0f]];
[anim setToValue:[NSNumber numberWithDouble:(M_PI * 2.0f)]];
[[imageView layer] addAnimation:anim forKey:@"wheeloRotation"];
}
I call this animtion method from my viewWillAppear method. When the app enters background and then re-appears, the animation does not Work anymore. Upon googling, I came up with this from Apple. All fine, I implemented Apple's recommendations like this in the same viewcontroller.m file that has the perform360rotation method for rotating the view.
-(void)pauseLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:[self.wheelView layer]];
layer.speed = 0.0;
layer.timeOffset = pausedTime;
NSLog(@"pauseLayer:paused time = %f",pausedTime);
}
-(void)resumeLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = [layer timeOffset];
NSLog(@"resumeLayer:paused time = %f",pausedTime);
layer.speed = 1.0;
layer.timeOffset = 0.0;
layer.beginTime = 0.0;
CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:[self.wheelView layer]] - pausedTime;
layer.beginTime = timeSincePause;
}
Again, on googling, I saw that the general consensus was that I call the pause and resume methods from the AppDelegate. So I did them like this (lVC is the viewcontroller.m class that has I mentioned at the start of this question. The pauseLayer and resumeLayer methods are being called from inside its viewWillAppear and viewWillDisappear methods):
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[lVC viewWillDisappear:YES];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[lVC viewWillAppear:YES];
}
No dice yet. The animation still does not resume when app re-enters foreground. Is there something that I am doing wrong?
调用viewWillAppear
可能会导致其他副作用,并且通常不是开始动画的好地方,请尝试侦听UIApplicationWillEnterForegroundNotification
并在处理程序中添加resumeLayer: