Show user progress with a Lottie animation

Follow this recipe to display the user’s progress as a Lottie animation — for example, a ring that fills up to indicate their daily streak. Your app renders the animation as a native Lottie view in a custom element.

Before you start

  • Update your app to Adapty Capacitor SDK 4.4 or later. Earlier SDK versions show the fallback content for every custom element.
  • Set up your app to fetch and display flows.
  • Set up the native code of your app for custom elements, as in the Capacitor guide.
  • On iOS, add Lottie to your app target in Xcode with Swift Package Manager, from https://github.com/airbnb/lottie-spm.git.
  • On Android, set up your Android project, including Jetpack Compose. The animation view in this recipe is a composable. Add Compose Foundation to your app with Gradle, from androidx.compose.foundation:foundation, without a version. The Compose BOM of io.adapty:android-ui sets the version. Add Lottie for Jetpack Compose from com.airbnb.android:lottie-compose.

Prepare a Lottie animation in .json format, or download the sample streak_ring.json. The app plays the animation from the start and stops it in proportion to the progress, such as halfway through for 50%. To show the exact progress, the animation needs:

  • No progress on its first frame, and full progress on its last frame.
  • A steady speed, with no easing. If the animation starts slowly and then speeds up, it shows less than half of the progress halfway through.

1. Add the custom element to the screen

In the Flow & Paywall Builder, add a custom element to a flow screen, and set it up for the animation:

  • Type: lottie_animation.
  • ID: streak_ring. In this recipe, the ID is also the name of the animation file.
  • Height: Keep the default Fixed height. The animation scales to fit the custom element.

Inside the custom element, add an Image with a still picture of the ring. Users see it as the fallback when their version of your app doesn’t play the animation.

2. Add the animation file to your app

Your native code reads the animation file from your iOS and Android projects, not from the assets of your web app:

  • iOS: Add the file to your app target in Xcode.
  • Android: Put the file in android/app/src/main/assets, the assets folder of your Android app module. Keep it at the root of this folder, not in a subfolder.

The file name without .json must match the ID of the custom element, such as streak_ring.json for streak_ring.

3. Create the animation view

Create a model for the streak, and a view that plays the animation. Your app updates the model when the streak changes. The view reads the model, so the ring shows the current streak when the screen opens:

import Lottie
import SwiftUI

// The streak that your app keeps up to date
@MainActor
final class StreakStore: ObservableObject {
    @Published var currentStreak = 0 // days in a row
}

struct StreakRingView: View {
    let animation: LottieAnimation
    @ObservedObject var streakStore: StreakStore

    // 7 days fill the ring: from 0 for an empty ring to 1 for a full one
    private var progress: AnimationProgressTime {
        min(AnimationProgressTime(streakStore.currentStreak) / 7, 1)
    }

    var body: some View {
        LottieView(animation: animation)
            .resizable()
            .playing(.fromProgress(0, toProgress: progress, loopMode: .playOnce))
    }
}

.playing(.fromProgress(0, toProgress: progress, loopMode: .playOnce)) fills the ring once, from empty up to progress.

4. Match the animation to the custom element

In your app-wide resolver, add a property for the streak model. Then return the animation view for the lottie_animation Type and the streak_ring ID. The highlighted lines show what to add or change. If your app has no app-wide resolver yet, copy the whole code:

import AdaptyUIBuilder
import Lottie
import SwiftUI

struct CustomElementsResolver: AdaptyUICustomElementsResolver {
    let streakStore: StreakStore

    func view(
        forType type: String,
        id: String,
        context: AdaptyUICustomElementContext
    ) -> AnyView? {
        switch type {
        case "lottie_animation" where id == "streak_ring":
            guard let animation = LottieAnimation.named(id) else {
                return nil // no animation file: show the fallback
            }
            return AnyView(StreakRingView(animation: animation, streakStore: streakStore))
        // the other cases of your resolver
        default:
            return nil
        }
    }
}

Put the streak_ring case before any other lottie_animation case, because Swift only runs the first case that matches. If the app bundle has no file for the ID, the resolver returns nil, and users see the fallback.

Create the resolver with the streak model, and set it as the app-wide resolver at app launch:

In AppDelegate.swift, add a property for the streak model, and set the resolver in the application(_:didFinishLaunchingWithOptions:) method. The highlighted lines show what to add. Keep the rest of the AppDelegate class as it is:

import AdaptyUI
import UIKit
import Capacitor

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    // the streak model that your app updates
    let streakStore = StreakStore()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        AdaptyUI.setCustomElementsResolver(CustomElementsResolver(streakStore: streakStore))
        // the rest of your launch code
        return true
    }
}

5. Send the streak from your JavaScript code

Your JavaScript code keeps the streak, and the native views read it from the streak model. To update the model, send the streak to your native code through a local Capacitor plugin . The plugin has an implementation for each platform and a JavaScript interface.

Implement the plugin for each platform:

In the App target in Xcode, create the plugin. It updates the streak model in your AppDelegate class:

import Capacitor
import UIKit

@objc(StreakStorePlugin)
public class StreakStorePlugin: CAPPlugin, CAPBridgedPlugin {
    public let identifier = "StreakStorePlugin"
    public let jsName = "StreakStore"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "setStreak", returnType: CAPPluginReturnPromise)
    ]

    @objc func setStreak(_ call: CAPPluginCall) {
        let days = call.getInt("days") ?? 0
        Task { @MainActor in
            (UIApplication.shared.delegate as? AppDelegate)?.streakStore.currentStreak = days
        }
        call.resolve()
    }
}

Create a subclass of CAPBridgeViewController that registers the plugin in its capacitorDidLoad method. If your app already has a subclass of CAPBridgeViewController, register the plugin there instead:

import Capacitor
import UIKit

class MyViewController: CAPBridgeViewController {
    override open func capacitorDidLoad() {
        bridge?.registerPluginInstance(StreakStorePlugin())
    }
}

To make the app use this subclass, in SceneDelegate.swift, replace CAPBridgeViewController() with MyViewController(). If your project has no SceneDelegate.swift, set the custom class of the Bridge View Controller in Main.storyboard to MyViewController instead, as in Custom ViewController.

In your JavaScript code, register the plugin. Then send the streak at app launch, and each time the streak changes:

import { registerPlugin } from '@capacitor/core';

interface StreakStorePlugin {
  setStreak(options: { days: number }): Promise<void>;
}

// the name matches the jsName on iOS and the plugin name on Android
const StreakStore = registerPlugin<StreakStorePlugin>('StreakStore');

// call at app launch, and each time the streak changes
export async function sendStreak(days: number) {
  await StreakStore.setStreak({ days });
}

6. Test on a device

The Flow & Paywall Builder can’t run your app code, so its canvas only shows the fallback. To preview the animation:

  1. Publish the flow. To see the latest published version instead of a cached one, register the device as a test device.
  2. Run a build of your app that includes the resolver. Set the streak to 0 days, open the screen, and verify that the ring stays empty. Repeat with 4 and 7 days, and verify that the ring fills up to each value.

To test the fallback, remove the animation file from the build, and open the screen again.

To find out why the fallback appears instead of the animation, follow the instructions in the Test on a device section of the Capacitor guide.