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.