1
votes

I'm trying to implement an animationView using Lottie & SwiftUI.

this is my code :

import SwiftUI
import Lottie

struct ContentView: View {
var body: some View {

    AnimationsView()
    }
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
    ContentView()
}
}
struct AnimationsView : UIViewRepresentable {

func makeUIView(context: UIViewRepresentableContext<AnimationsView>) -> 
AnimationView {
   let aniView = AnimationView()
    let animation = Animation.named("Switch", subdirectory: "TestAnimations")
    aniView.animation = animation
    aniView.play()
    return aniView
    }
func updateUIView(_ uiView: AnimationView, context: 
UIViewRepresentableContext<AnimationsView>) {

    }
}

I've added the last version of Lottie as Swift Package dependencies. The preview in SwiftUI show me the animation and everything is OK at this state. I'm not using Storyboard it should open the View and the lottie animation inside.

What I have at this state

When I run the app, The app crash and I have this message code : Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

enter image description here

As I understand it there's something not initialized and the return value is null ... I'm trying to do the same thing as in this tutorial : https://www.youtube.com/watch?v=iuEqGyBYaE4

What's wrong?

thank you in advance

1

1 Answers

2
votes

This is a known issue. You can see here and here

There is a workaround by setting dead code stripping to no in your app's target

DEAD_CODE_STRIPPING = NO

enter image description here

Similarly you may need to also change how you access the lottie file from the bundle.

struct AnimationsView: UIViewRepresentable {

    func makeUIView(context: UIViewRepresentableContext<AnimationsView>) -> AnimationView {
        let aniView = AnimationView()
        // its always a good idea to check that the file exists and throw an error if it doesn't. 
        guard let animation = Animation.named("Switch", bundle: .main) else {
            fatalError("Couldn't load animation")
        }
        aniView.animation = animation
        aniView.loopMode = .repeat(10.0)
        return aniView
    }

    func updateUIView(_ uiView: AnimationsView.UIViewType, context: UIViewRepresentableContext<AnimationsView>) {

    }

}