Im using Lottie animation in my app and im trying to keep the animation running in the background when i exit the app and open it again (not force close) ..
I was able to do so successfully, but the problem is the animation stops when i select different tab bar item and go back to the tab bar item that has the animation view.
this is my code.
import UIKit
import Lottie
import UserNotifications
import NotificationCenter
class HomeViewController: UIViewController {
@IBOutlet weak var animationView: UIView!
var animation : AnimationView?
override func viewDidLoad() {
super.viewDidLoad()
setupAnimation()
NotificationCenter.default.addObserver(self, selector: #selector(applicationEnterInForground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
func setupAnimation() {
animation = AnimationView(name: "cong")
animation?.frame = self.animationView.bounds
self.animationView.addSubview(animation!)
animation?.loopMode = .loop
animation?.contentMode = .scaleAspectFit
animation?.play()
}
@objc func applicationEnterInForground() {
if animation != nil {
if !(self.animation?.isAnimationPlaying)! {self.animation?.play()}}
}
}
Swift 5
There is a property, that can be set & it will restore your Lottie animation:
yourAnimationView.backgroundBehavior = .pauseAndRestore
By default, this property is set to .pause
Better, use viewWillAppear/viewDidAppear
to start the animation again and remove observing the willEnterForegroundNotification
.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if self.animation?.isAnimationPlaying == false {
self.animation?.play()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With