Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lottie animation stopped when i tap on different tab bar item

Tags:

ios

swift

lottie

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()}}
    }
}
like image 413
Mustafa Aljaburi Avatar asked Oct 23 '19 07:10

Mustafa Aljaburi


2 Answers

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

like image 77
Krekin Avatar answered Sep 25 '22 01:09

Krekin


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()
    }
}
like image 20
Kamran Avatar answered Sep 25 '22 01:09

Kamran