How to fix performance issue while loading new animation in Lottie?
Asked Answered
T

1

7

I am trying to make a simple game with Xcode 11.2 which contains an animated loop background and a view which shows and changes various animations from several Lottie JSON files in project.

When I click the "Next" button to change the view animation, background view which is looping gets stuck for a second until the next animation inside the view is loaded an everything in the app freezes at the same time just like the background animation.

CPU usage varies from 30% to 63%.

I don't like to complicate the question, so I am just showing the way I used Lottie.

@IBAction func SubmitButtonAction(_ sender: UIButton) {
    
    showNextQuestion()
    
}

func showNextQuestion()->(){
    
    myTimer.invalidate()
    startCountdown(fromTime: 15)
    Manager.generateQuestion()
    lblLevel.text = String(Manager.questionNumber) + "/" + String(DataModel.Questions.count)
    nIndex = 0

    
    let animation = AnimationView(name: Manager.currentImage)
    
    animation.loopMode = .loop
    animation.play()
    animation.backgroundColor = UIColor.clear
   animation.frame = self.AnimView.bounds
    animation.backgroundBehavior = .pauseAndRestore
    if AnimView.subviews.isEmpty{
        self.AnimView.addSubview(animation)
    }
    else {
        for one in imgImageView.subviews{
            one.removeFromSuperview()
        }
        self.AnimView.addSubview(animation)
    }
   
    AnswerCollectionView.reloadData()
    RandomCollectionView.reloadData()
    
}

I am interested in suggestions as to what the problem is related to - could it be related to a threading issue?

Trioecious answered 28/11, 2019 at 6:58 Comment(5)
Run all UI updates on main thread DispatchQueue.main.asyncTsui
Rather than recreating the animation each time it plays how about creating it once and showing and hiding it by isHidden property.Gigue
its not a good idea when i use it in a quiz like app which consists of lot of lottie files in an array may be...i just want to be safe from every memory issuesTrioecious
i think @user3344236 is rightTrioecious
can someone explain how the exact code should look likeTrioecious
A
0

In response to Jaseel.Dev, I created a function that returned a LottieView with the following:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            withAnimation(.spring()) {
                LottieView(name: animation)
            }
        }
Aeronautics answered 24/9, 2022 at 13:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.