I'm making a simple app testing Lottie animation library in swift. The code is perfectly running when i lunch the app for the first time. But if i relaunch it from the background, the animation stops.
How do i keep the animation running in the background so when i switch to another app and back again, i see the animation working.
I just started learning swift, so i apologize in advance.
import UIKit
import Lottie
class ViewController: UIViewController {
@IBOutlet weak var animationView: AnimationView!
override func viewDidLoad() {
super.viewDidLoad()
SetupAnimation()
}
func SetupAnimation() {
let animationView = AnimationView(name: "kiss")
animationView.frame = self.animationView.frame
self.animationView.addSubview(animationView)
animationView.loopMode = .autoReverse
animationView.contentMode = .scaleAspectFit
animationView.play()
}
}
There are one simple thing which will help you to play your animation.
Add following notification of willEnterForegroundNotification
in your view controller where you have added animation.
Another thing, Declare Lottie's AnimationView's instance globally. See following code
class MyClassVC: UIViewController {
@IBOutlet weak var animationView : UIView!
var animation : AnimationView?
func setupAnimation() {
animation = AnimationView(name: "kiss")
animation?.frame = self.animationView.bounds
self.animationView.addSubview(animation!)
animation?.loopMode = .autoReverse
animation?.contentMode = .scaleAspectFit
animation?.play()
}
@objc func applicationEnterInForground() {
if animation != nil {
if !(self.animation?.isAnimationPlaying)! {
self.animation?.play()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupAnimation()
NotificationCenter.default.addObserver(self, selector: #selector(applicationEnterInForground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
}
This will play animation when application come in foreground from background.