Fix issue where LottieView animation would restart from beginning after backgrounding app by calda · Pull Request #2237 · airbnb/lottie-ios
This PR fixes an issue where the SwiftUI LottieView would always restart playback from the beginning after backgrounding the app, even when using a LottieBackgroundBehavior like continuePlaying or pauseAndRestore.
When using the default LottieView.init(animation:) initializer, the animation expression is recomputed on every view update. Since these calls include a AnimationCacheProvider, this simply returns the existing LottieAnimation instance rather than actually loading the animation from disk on every update.
DefaultAnimationCache is backed by an NSCache. The issue here is that NSCache actually evicts all of the cached items when the app is backgrounded (regardless of if there is memory pressure or not). I hadn't heard about this behavior before now!
This means that after backgrounding the app and then foregrounding it again, on the following SwiftUI view update:
- the animation will no longer be present in the cache
- the animation will be loaded from disk, resulting in a new
LottieAnimationinstance LottieViewwill callview.loadAnimation(animationSource)- The "new" animation will start playing from the beginning.
We can fix this by using the LRUCache library as a replacement for NSCache. LRUCache works very similarly to NSCache, and automatically handled responding to memory pressure. LRUCache doesn't include this "reset when backgrounded" behavior, though, which avoids this specific issue.
| Before | After |
|---|---|
![]() |
![]() |

