Pause and resume the main animation when the application enters and leaves the background

I have a simple CABasicAnimation connected as an endless animation (I have a wheel that I keep spinning forever). Here is the method in which I set this 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 animation method from my viewWillAppear method. When the application enters the background and then reappears, the animation no longer works. After googling, I came up with this from Apple. Everything is fine, I implemented Apple recommendations like this in the same viewcontroller.m file, which has a perform360rotation method to rotate 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, when searching on Google, I saw that the general consensus was that I pause and resume methods from AppDelegate. So I did it like this (lVC is the viewcontroller.m class that I mentioned at the beginning of this question. The pauseLayer and resumeLayer methods are called from within its viewWillAppear and viewWillDisappear methods):

 - (void)applicationDidEnterBackground:(UIApplication *)application { [lVC viewWillDisappear:YES]; } - (void)applicationWillEnterForeground:(UIApplication *)application { [lVC viewWillAppear:YES]; } 

No dice yet. Animation does not resume when the application returns to the forefront. Is there something I'm doing wrong?

+4
source share
1 answer

Calling viewWillAppear can cause other side effects and is generally not a good place to start an animation, try listening to UIApplicationWillEnterForegroundNotification and add a resumeLayer: to the handler.

+1
source

Source: https://habr.com/ru/post/1394084/


All Articles