从文档目录读取Lottie动画的正确方法是什么

问题描述

我试图将json存储在文档目录中,然后读取以显示Lottie动画。

这就是我在文档中写入json的方式

        if let documentDirectory = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first {
            let pathWithFilename = documentDirectory.appendingPathComponent("myJsonString.json")
            
            do {
                try jsonString.write(to: pathWithFilename,atomically: true,encoding: .utf8)
            } catch {
                
            }
        }
        

这就是我的阅读方式

            let checkmarkAnimation =  AnimationView(filePath: "\(pathWithFilename)")
            animationView.contentMode = .scaleAspectFit
            self.animationView.addSubview(checkmarkAnimation)
            checkmarkAnimation.frame = self.animationView.bounds
            checkmarkAnimation.loopMode = .loop
            checkmarkAnimation.play()

我完全知道这是可以正常工作的json,当我打印Data(contentsOf:pathWithFilename)时,它也会打印实际的json,但是当我使用AnimationView(filePath :)在动画中分配它时,它将无法工作。

解决方法

您使用filePath的方式存在问题。因为pathWithFilename是URL,所以不要像"\(pathWithFilename)"那样使用它,而应该像-pathWithFilename.path那样使用它。

以下将为您工作,

let checkMarkAnimation =  AnimationView(filePath: pathWithFilename.path)
animationView.contentMode = .scaleAspectFit
self.animationView.addSubview(checkMarkAnimation)
checkMarkAnimation.frame = self.animationView.bounds
checkMarkAnimation.loopMode = .loop
checkMarkAnimation.play()