How to animate the CABasicAnimation in background after the home button is pressed?

Swift 4.2 Updated

Ah I figured it out - use this and all the cases like stopping after going into the background will be fixed.

animation.isRemovedOnCompletion = false

Try this,

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAnimation:) name:UIApplicationWillEnterForegroundNotification object:nil];

}

- (void)addAnimation:(NSNotification *)notificaiton
 {
 CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
 animation.fromValue = [NSNumber numberWithFloat: 2*M_PI];
 animation.toValue = [NSNumber numberWithFloat:0.0f];
 animation.duration = 4.0f;
 animation.repeatCount = INFINITY;
 [imageLeft.layer addAnimation:animation forKey:@"SpinAnimation"];
 [imageRight.layer addAnimation:animation forKey:@"SpinAnimation"];
 }

When you leave the app, all animations are removed from their layers: the system calls removeAllAnimations on every layer. So if you want to continue animation, then u can listen to UIApplicationDidBecomeActiveNotification and start the animation again.

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (![_imageLeft.layer animationForKey:@"SpinAnimation"])
    {
         CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
         animation.fromValue = [NSNumber numberWithFloat: 2*M_PI];
         animation.toValue = [NSNumber numberWithFloat:0.0f];
        animation.duration = 4.0f;
        animation.repeatCount = INFINITY;
        [_imageLeft.layer addAnimation:animation forKey:@"SpinAnimation"];
    }


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAnimation:) name:UIApplicationDidBecomeActiveNotification object:nil];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)addAnimation:(NSNotification *)notificaiton
{
   if (_imageLeft && ![_imageLeft.layer animationForKey:@"SpinAnimation"])
   {
       CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        animation.fromValue = [NSNumber numberWithFloat: 2*M_PI];
        animation.toValue = [NSNumber numberWithFloat:0.0f];
        animation.duration = 4.0f;
        animation.repeatCount = INFINITY;
        [_imageLeft.layer addAnimation:animation forKey:@"SpinAnimation"];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}