ios - 在后台运行应用程序的最佳方式是什么

标签 ios swift lottie

我正在快速制作一个简单的应用程序来测试 Lottie 动画库。当我第一次使用该应用程序时,代码运行良好。但是如果我从后台重新启动它,动画就会停止。

如何让动画在后台运行,以便当我切换到另一个应用程序并再次返回时,我看到动画正在运行。

我刚开始学习swift,所以我提前道歉。

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()
   }
}

最佳答案

有一件简单的事情可以帮助您播放动画。

在添加了动画的 View Controller 中添加以下 willEnterForegroundNotification 通知。

另一件事,全局声明 Lottie 的 AnimationView 实例。看下面代码

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)
    }
}

这将在应用程序从后台进入前台时播放动画。

关于ios - 在后台运行应用程序的最佳方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57899272/

相关文章:

ios - 无法声明另一个窗口

ios - Swift - 防止计时器重复

ios - 在单击不同的 TableView 单元之前,TableView 单元不加载 View Controller

java - 洛蒂错误 : "java.lang.IllegalStateException: Unable to parse composition"

ios - 使用 AKKeyboardView 的钢琴音符

android - 如何使用 Flutter 将整数存储到 Firestore

ios - iOS 版 Firefox 是否支持 WebAssembly?

ios - 解析 - callFunctionInBackground 在 [__NSTaggedDate UTF8String] 上使应用程序崩溃 - 但当我提交应用程序时却没有崩溃

c# - 如何为 Xamarin.forms 实现 Lottie?