Interactive Animations in SwiftUI

10 minutes · For iOS developers

This guide shows how a Kineto animation fits into a SwiftUI app: your code sets named inputs, and the file decides which animation plays. You can change the motion without changing your view code, as long as the input names stay the same.

For every API call, UIKit and error handling, see iOS Playback.

Agree on the inputs first

The inputs are the contract between the designer and the developer. Write them down before anyone starts animating.

Your app knows Input Type
A one-time event happened didSucceed Trigger
Something is on or off isLoading Bool

Use names that describe your app, not the animation. isLoading still makes sense when the animation changes, but spinFast might not.

Transitions can’t compare numbers. If your app has a value like speed, turn it into bools in your code. See the character example.

When you export the .kvk, keep the handoff option on. The handoff notes list the machine id and the inputs.

Show the player

KinetoPlayer holds the animation, and KinetoPlayerViewController draws it. SwiftUI needs a small wrapper:

struct KinetoPlayerView: UIViewControllerRepresentable {
    let player: KinetoPlayer

    func makeUIViewController(context: Context) -> KinetoPlayerViewController {
        KinetoPlayerViewController(player: player)
    }

    func updateUIViewController(_ controller: KinetoPlayerViewController, context: Context) {}
}

The view controller draws every frame and handles touches on the artwork, so taps on targets work without more code.

Connect an app event

Keep one KinetoPlayer in your view, and set inputs from your actions. This example uses cody.kvk, the file from the homepage. It holds the input for 0.22 seconds, like a quick tap.

private func wink(_ input: String) {
    guard let player else { return }
    do {
        try player.setBool(true, input: input, in: Self.machineID)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.22) {
            try? player.setBool(false, input: input, in: Self.machineID)
        }
    } catch {
        errorMessage = String(describing: error)
    }
}

The bool has to go back to false, because that’s Cody’s condition for returning to Idle. A state doesn’t return on its own when its clip ends.

The complete view is in iOS Playback. We ran it on a physical iPad.

Test on a device

Use a real device. On the iOS Simulator, the player view closes the app, because the Simulator’s Metal lacks a feature the renderer needs.