I have an app with an UIImageView (named ivBanner) that will show one image (of many images) at a time in a fadein/fadeout manner (in a loop). This is the code that does this animation/transitions:
func showBanners(ivBanner: UIImageView) {
CATransaction.begin()
CATransaction.setAnimationDuration(animationDuration)
CATransaction.setCompletionBlock {
let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(self.switchingInterval * NSTimeInterval(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {
self.showBanners(ivBanner)
}
}
let transition = CATransition()
transition.type = kCATransitionFade
ivBanner.layer.addAnimation(transition, forKey: kCATransition)
ivBanner.image = images[index]
CATransaction.commit()
index = index < images.count - 1 ? index + 1 : 0
}
This works perfectly.
My problem is that when I tap the home-button, and then reopens the app, I want the animation to continue. But at this time, there may be new images to be shown. I.e. I read the images to be shown from an API every time the app starts and reopens.
But when I just call the function above again after the app reopens, the animation no longer works fine. I guess this is because the images previously animated is still in the animation “queue”, and the new images (and animations) is just added.
I think this could be solved by removing the whole animation in applicationDidEnterBackground and then regenerate a new animation in applicationWillEnterForeground (or in the delegate of the API-call that is called every time the app reopens).
I just don´t know how to implement this. I have tried with removeAllAnimations, but that does not do the job.
I thought maybe a solution could be to remove the layer of the ImageView and then add a new layer at each reopen, but I have not been able to implement this.