Search code examples
iosswiftlottie

Lottie animation stopped when i tap on different tab bar item


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.

Screenshot

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()}}
    }
}

Solution

  • 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()
        }
    }