Fix issue where LottieView animation would restart from beginning after backgrounding app #2237
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR fixes an issue where the SwiftUI
LottieView
would always restart playback from the beginning after backgrounding the app, even when using aLottieBackgroundBehavior
likecontinuePlaying
orpauseAndRestore
.When using the default
LottieView.init(animation:)
initializer, the animation expression is recomputed on every view update. Since these calls include aAnimationCacheProvider
, this simply returns the existingLottieAnimation
instance rather than actually loading the animation from disk on every update.DefaultAnimationCache
is backed by anNSCache
. The issue here is thatNSCache
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:
LottieAnimation
instanceLottieView
will callview.loadAnimation(animationSource)
We can fix this by using the
LRUCache
library as a replacement forNSCache
.LRUCache
works very similarly toNSCache
, and automatically handled responding to memory pressure.LRUCache
doesn't include this "reset when backgrounded" behavior, though, which avoids this specific issue.