0

I am animating a view using UIViewAnimation with completion block. When app goes to background mode need to pause the animation and resume it from where it paused in foreground mode. I am using bellow methods for pause and resume:-

func resume() {
    let pausedTime: CFTimeInterval = layer.timeOffset
    layer.speed = 1.0
    layer.timeOffset = 0.0
    layer.beginTime = 0.0
    let timeSincePause: CFTimeInterval = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
    layer.beginTime = timeSincePause
}
func pause() {
    let pausedTime: CFTimeInterval = layer.convertTime(CACurrentMediaTime(), from: nil)
    layer.speed = 0.0
    layer.timeOffset = pausedTime
}

Those two methods works fine if app is in foreground. but if app goes to background, animation finished and completion block called first then pause method called but not worked as animation already finished. I used UIApplication.willEnterForegroundNotification and UIApplication.didEnterBackgroundNotification

According to this answer use Core Animation instead of UIViewAnimation and then the resume/pause will work. But I didn't get the way to use CABasicAnimation instead of UIView animation.

        UIView.animate(withDuration: duration, delay: 0.0, options: [.curveLinear], animations: {[weak self] in
        if let _self = self {
            _self.frame.size.width = width
        }
    }) { [weak self] (finished) in
        // do something after finished animation
    }

If use Core Animation how can I do it? else is there any solution for UIView animation background pause and foreground resume.

Shariif Islam
  • 259
  • 1
  • 2
  • 15

1 Answers1

0

See this thread for a fairly detailed discussion:

How to pause and resume UIView.animateWithDuration

By far the easiest and cleanest way to pause and resume animation is to use a UIViewPropertyAnimator,as mentioned in one of those answers.

You should be able to capture the percent complete of the animation when you get notified that your app is being suspended, and then write code to re-establish the animation when your app resumes, and set it to the same point in the animation.

Duncan C
  • 128,072
  • 22
  • 173
  • 272