0

I'm making a simple app testing Lottie animation library in swift. The code is perfectly running when i lunch the app for the first time. But if i relaunch it from the background, the animation stops.

How do i keep the animation running in the background so when i switch to another app and back again, i see the animation working.

I just started learning swift, so i apologize in advance.

import UIKit
import Lottie

class ViewController: UIViewController {
    @IBOutlet weak var animationView: AnimationView!

    override func viewDidLoad() {
        super.viewDidLoad()
        SetupAnimation()
    }

func SetupAnimation() {
        let animationView = AnimationView(name: "kiss")
        animationView.frame = self.animationView.frame
        self.animationView.addSubview(animationView)
        animationView.loopMode = .autoReverse
        animationView.contentMode = .scaleAspectFit
        animationView.play()
   }
}
Mustafa Aljaburi
  • 1,485
  • 2
  • 7
  • 8

2 Answers2

1

There are one simple thing which will help you to play your animation.

Add following notification of willEnterForegroundNotification in your view controller where you have added animation.

Another thing, Declare Lottie's AnimationView's instance globally. See following code

class MyClassVC: UIViewController {

    @IBOutlet weak var animationView : UIView!
    var animation : AnimationView?

    func setupAnimation() {
        animation = AnimationView(name: "kiss")
        animation?.frame = self.animationView.bounds
        self.animationView.addSubview(animation!)
        animation?.loopMode = .autoReverse
        animation?.contentMode = .scaleAspectFit
        animation?.play()
    }

    @objc func applicationEnterInForground() {
        if animation != nil {
            if !(self.animation?.isAnimationPlaying)! {
                self.animation?.play()
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupAnimation()
        NotificationCenter.default.addObserver(self, selector: #selector(applicationEnterInForground), name: UIApplication.willEnterForegroundNotification, object: nil)
    }
}

This will play animation when application come in foreground from background.

Sagar Chauhan
  • 5,715
  • 2
  • 22
  • 56
0

Try

override func viewDidAppear(animated: Bool)
{
    super.viewDidAppear(animated: animated)
    animation.play()
}

Another thing is wring here

var animation: AnimationView!

func SetupAnimation() {
        animation = AnimationView(name: "kiss")
        animation.frame = self.animationView.frame
        self.animationView.addSubview(animation)
        animation.loopMode = .autoReverse
        animation.contentMode = .scaleAspectFit
   }

I don't see any purpose of animationView to be kind of AnimationView. You can change it to UIView.

@IBOutlet weak var animationView: AnimationView!

to

@IBOutlet weak var animationView: UIView!
Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44