title: Restoring animation where it left off when app resumes from background
body: <p>I have an endlessly looping <code>CABasicAnimation</code> of a repeating image tile in my view: </p>
  
  <pre><code>a = [CABasicAnimation animationWithKeyPath:@"position"];
  a.timingFunction = [CAMediaTimingFunction 
                        functionWithName:kCAMediaTimingFunctionLinear];
  a.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)];
  a.toValue = [NSValue valueWithCGPoint:CGPointMake(image.size.width, 0)];
  a.repeatCount = HUGE_VALF;
  a.duration = 15.0;
  [a retain];
  </code></pre>
  
  <p>I have tried to "pause and resume" the layer animation as described in <a href="http://developer.apple.com/library/ios/#qa/qa1673/_index.html" rel="noreferrer">Technical Q&amp;A QA1673</a>. </p>
  
  <p>When the app enters background, the animation gets removed from the layer. 
  To compensate I listen to <code>UIApplicationDidEnterBackgroundNotification</code> and call <code>stopAnimation</code> and in response to <code>UIApplicationWillEnterForegroundNotification</code> call <code>startAnimation</code>.</p>
  
  <pre><code>- (void)startAnimation 
  {
      if ([[self.layer animationKeys] count] == 0)
          [self.layer addAnimation:a forKey:@"position"];
  
      CFTimeInterval pausedTime = [self.layer timeOffset];
      self.layer.speed = 1.0;
      self.layer.timeOffset = 0.0;
      self.layer.beginTime = 0.0;
      CFTimeInterval timeSincePause = 
        [self.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
      self.layer.beginTime = timeSincePause;
  }
  
  - (void)stopAnimation 
  {
      CFTimeInterval pausedTime = 
        [self.layer convertTime:CACurrentMediaTime() fromLayer:nil];
      self.layer.speed = 0.0;
      self.layer.timeOffset = pausedTime;    
  }
  </code></pre>
  
  <p>The problem is that it starts again at the beginning and there is ugly jump from last position, as seen on app snapshot the system took when application did enter background, back to the start of the animation loop.</p>
  
  <p>I can not figure out how to make it start at last position, when I re-add the animation. Frankly, I just don't understand how that code from QA1673 works: in <code>resumeLayer</code> it sets the layer.beginTime twice, which seems redundant. But when I've removed the first set-to-zero, it did not resume the animation where it was paused. This was tested with simple tap gesture recognizer, that did toggle the animation - this is not strictly related to my issues with restoring from background.</p>
  
  <p>What state should I remember before the animation gets removed and how do I restore the animation from that state, when I re-add it later?</p>