Lottie animation stopped when i tap on different tab bar item
Asked Answered
E

2

10

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()}}
    }
}
Erv answered 23/10, 2019 at 7:18 Comment(0)
G
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()
    }
}
Gluey answered 23/10, 2019 at 7:23 Comment(0)
S
40

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

Saldivar answered 10/12, 2020 at 16:3 Comment(2)
This appears to fix the issue. ThanksLoosen
When you are using Lottie, especially for TabBar should it be in one single color, or does support multi-colors? @Saldivar any idea on this. I currently received a Lottie with multiple colors and the tab bar do not support itIrrigation
G
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()
    }
}
Gluey answered 23/10, 2019 at 7:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.