9

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()}}
    }
}
Mustafa Aljaburi
  • 1,485
  • 2
  • 7
  • 8

2 Answers2

38

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

Krekin
  • 1,516
  • 1
  • 13
  • 24
  • This appears to fix the issue. Thanks – Vinayak Jan 27 '21 at 13:02
  • When you are using Lottie, especially for TabBar should it be in one single color, or does support multi-colors? @Krekin any idea on this. I currently received a Lottie with multiple colors and the tab bar do not support it – Gangadhar Feb 28 '22 at 20:20
8

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()
    }
}
Kamran
  • 14,987
  • 4
  • 33
  • 51