Lottie:无法获取带名称的动画

Lottie: Can't get Animation with name

我正在使用 Lottie 2.1.3、XCode 9 和 IOS 11。

当我尝试制作这样的动画时

var loadingView = LOTAnimationView(name: "preloader")

我正在处理这个错误:+[LOTComposition animationNamed:inBundle:]: 找不到动画

但是像下面这样的动画效果很好

var loadingView = LOTAnimationView(filePath: "/Users/username/Git/iOS/Swift/LottieTest/LottieTest/preloader.json")

这是我正在使用的 preloader.json https://www.lottiefiles.com/storage/datafiles/Hhw0wgYmETDTkxW/data.json

我做错了什么?

很有趣,但是你不想使用其他初始化方法,例如使用 json 文件吗?

我查看了 Lottie 的文档,但我似乎找不到这个初始化函数背后的解释 LOTAnimationView(name: "name")。正如我们在 Lottie 的示例中看到的那样,LottieLogo.json 文件与您在问题中提供的 json 文件以及我的文件相比具有不同的数据在我的项目中拥有 json 文件。

尽管如此,只需将您的 json 文件添加到您的项目中并读取它并使用 Lottie 的这个 init 函数 --> LOTAnimationView(json: jsonObject)

我在名为 GPKit https://github.com/glennposadas/gpkit-ios 的小项目中创建了一个读取 json 文件的函数 :D

public class GPJSONReader {

    /** Get the whole JSON object from a file
     *  @returns an optional dictionary [String: Any]?
     */

    public class func readJson(fileName: String, withBlock completion: ([String : Any]?) -> Void) {
        do {
            if let file = Bundle.main.url(forResource: fileName, withExtension: "json") {
                let data = try Data(contentsOf: file)
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                if let object = json as? [String : Any] {
                    GPLog(classSender: self, log: "JSON found as dictionary")
                    completion(object)
                } else {
                    GPLog(classSender: self, log: "JSON is invalid")
                    completion(nil)
                }
            } else {
                GPLog(classSender: self, log: "No file found!")
                completion(nil)
            }
        } catch {
            GPLog(classSender: self, log: error.localizedDescription)
            completion(nil)
        }
    }
}

然后像这样为 Lottie 使用上面的函数:

// Animate here...
GPJSONReader.readJson(fileName: "connecting", withBlock: { (jsonObject) in
    if let jsonObject = jsonObject {
        self.animationView = LOTAnimationView(json: jsonObject)
        self.animationView.loopAnimation = true
        self.animationView.play()
    }
})

我解决了我的问题。显然那是我的错。 为了使用 LOTAnimationView(name: "name") init 方法,您必须执行以下操作...

在您的 XCode 项目中,单击您的 preLoader.json 文件,然后在检查器中(Xcode 的右侧面板)单击 Target 中包含项目名称的复选框会员资格

我正在使用

  let animationView = LOTAnimationView(name: "servishero_loading")
            animationView.frame = CGRect(x: 0, y: 0, width: 300, height: 400)
            animationView.center = self.view.center
            animationView.contentMode = .scaleAspectFill

            view.addSubview(animationView)

            animationView.play()

我解决了我的问题,只需单击 servishero_loading.json 文件并在文件检查器 -> 目标成员 -> 选中项目目标名称的复选框。