在付费墙中显示交互式体重目标图表

按照以下步骤,在付费墙流程中以数据图表形式展示每位用户的预期体重变化。用户在用户引导流程中输入当前体重和目标体重,你的应用会收集这两个值。数据图表按周显示用户使用你的应用后可以预期的进展,从当前值变化到目标值。你的应用以原生视图的形式在自定义元素中渲染数据图表。在 iOS 上,视图使用 Swift Charts;在 Android 上,视图无需图表库即可绘制数据图表。

开始之前

  • 将您的应用更新至 Adapty Kotlin Multiplatform SDK 4.4.0-beta.1 或更高版本。早期 SDK 版本会为每个自定义元素显示备用内容。
  • 配置应用以获取和展示流程。
  • 按照 Kotlin Multiplatform 指南,为自定义元素配置应用的原生代码。
  • 在 iOS 上,沿数据图表拖动需要 iOS 17 或更高版本。在 iOS 16 上,用户可以看到折线,但无法沿其拖动。
  • 在 Android 上,配置 Android 项目,包括 Jetpack Compose。此方案中的数据图表是一个可组合项。如果您的应用未使用 Compose Multiplatform,请将 Compose Foundation 添加到 androidMain 依赖项中,来源为 androidx.compose.foundation:foundation,无需指定版本。版本由 io.adapty:android-ui 的 Compose BOM 统一管理。

创建两个独立的流程——一个用于用户引导,一个用于付费墙。将每个流程添加到对应的版位。本示例代码从 ID 为 weight_paywall 的版位获取付费墙流程。

1. 在用户引导流程中询问当前体重和目标体重

在流程与付费墙编辑工具中,向用户引导流程添加两个 Number 输入框:

  • 一个用于输入当前体重(千克),Element ID 设为 weight。
  • 一个用于输入目标体重(千克),Element ID 设为 goal_weight。

为确保您的应用在所有语言环境下以统一方式读取体重值,请在两个输入框的 Format 下拉菜单中选择 Integer。输入框会将用户输入的内容原样以文本形式发送给应用。本示例代码对 “70.5” 和 “70,5” 的处理方式不同,而整数没有小数分隔符。

为确保应用能接收到两个值,请在用户引导流程的末尾添加一个不包含任何输入框的屏幕。在该屏幕上添加一个按钮,并为其配置 Close flow 操作。输入框会在失去焦点或用户切换到另一个屏幕时发送其值。

2. 将自定义元素添加到付费墙页面

在付费墙流程中,向某个屏幕添加自定义元素,并为数据图表进行配置:

  • Type:line_chart。
  • ID:weight_goal。
  • Height:保持默认的 Fixed 高度。图表将填满整个自定义元素。

请将自定义元素放在不响应触摸的容器之外(如轮播图),以确保只有图表响应拖动操作。

在自定义元素内部,添加一个包含示例体重图表的Image。当用户所使用的 app 版本无法显示图表时,该图片将作为备用内容展示。

3. 在应用中保存当前体重和目标体重

从用户引导流程的 flow_user_input 事件中收集当前体重和目标体重,具体方法参见处理流程中的数据。要判断用户是否到达最后一屏,可监听 flow_screen_showed 事件中 is_last_screen 是否为 true。当用户引导流程在该屏后关闭时,将当前体重和目标体重传入 showWeightPaywall,即携带当前体重和目标体重打开付费墙流程的函数。

一个观察者接收两个流程的事件。在展示用户引导流程之前,请通过 AdaptyUI.setFlowsEventsObserver 注册它。新注册的观察者会替换之前的观察者:如果你的应用已经注册了观察者,请将 WeightFlowsObserver 的代码合并进去。showWeightPaywall 函数来自第 6 步。


class WeightFlowsObserver : AdaptyUIFlowsEventsObserver {
    private val enteredWeights = mutableMapOf<String, String>()
    private var reachedLastScreen = false

    override fun flowViewDidReceiveAnalyticEvent(
        view: AdaptyUIFlowView,
        name: String,
        paramsJsonString: String,
    ) {
        val params = Json.parseToJsonElement(paramsJsonString).jsonObject
        if (name == "flow_screen_showed" && params["is_last_screen"]?.jsonPrimitive?.booleanOrNull == true) {
            reachedLastScreen = true
            return
        }
        if (name != "flow_user_input") return
        val elementId = params["element_id"]?.jsonPrimitive?.contentOrNull ?: return
        val value = params["value"]?.jsonPrimitive?.contentOrNull ?: return
        enteredWeights[elementId] = value
    }

    override fun flowViewDidDisappear(view: AdaptyUIFlowView) {
        // This observer receives events from both flows. Reset the entered
        // current and goal weight whenever a flow disappears, so that the paywall doesn't open
        // again when the user closes it.
        val weights = enteredWeights.toMap()
        val finished = reachedLastScreen
        enteredWeights.clear()
        reachedLastScreen = false

        // number inputs send their values as strings
        val currentWeight = weights["weight"]?.toDoubleOrNull()
        val goalWeight = weights["goal_weight"]?.toDoubleOrNull()
        if (!finished || currentWeight == null || goalWeight == null) return

        showWeightPaywall(currentWeight, goalWeight) // defined in step 6
    }
}

// call at app launch, before you present the onboarding flow
fun registerWeightFlowsObserver() {
    AdaptyUI.setFlowsEventsObserver(WeightFlowsObserver())
}

4. 创建数据图表视图

创建一个体重计划的模型,以及一个包含数据图表的视图。该计划每周有一条记录,从当前体重到目标体重。当用户沿数据图表拖动时,视图会标记触摸点所在的那一周,并显示该周的预计体重:


struct WeightPlan {
    let entries: [WeightEntry]

    // One entry per week, from the current weight to the goal weight
    init(currentWeight: Double, goalWeight: Double) {
        let weeklyChange = 0.5 // kg per week
        let startDate = Date.now
        let weeks = Int((abs(goalWeight - currentWeight) / weeklyChange).rounded(.up))
        let step = goalWeight < currentWeight ? -weeklyChange : weeklyChange
        entries = (0...weeks).map { week in
            WeightEntry(
                date: startDate.addingTimeInterval(Double(week) * 7 * 24 * 60 * 60),
                kilograms: week == weeks ? goalWeight : currentWeight + step * Double(week)
            )
        }
    }
}

struct WeightEntry: Identifiable {
    let date: Date
    let kilograms: Double
    var id: Date { date }
}

@available(iOS 16.0, *) // Swift Charts needs iOS 16
struct WeightGoalChart: View {
    let entries: [WeightEntry]
    @State private var selectedDate: Date?

    // The entry closest to the date that the user drags to
    private var selectedEntry: WeightEntry? {
        guard let selectedDate else { return nil }
        return entries.min {
            abs($0.date.timeIntervalSince(selectedDate)) < abs($1.date.timeIntervalSince(selectedDate))
        }
    }

    var body: some View {
        if #available(iOS 17.0, *) {
            chart.chartXSelection(value: $selectedDate)
        } else {
            chart // iOS 16: no drag selection
        }
    }

    private var chart: some View {
        Chart {
            ForEach(entries) { entry in
                LineMark(
                    x: .value("Date", entry.date),
                    y: .value("Weight", entry.kilograms)
                )
            }
            if let selectedEntry {
                RuleMark(x: .value("Date", selectedEntry.date))
                    .foregroundStyle(.gray.opacity(0.3))
                PointMark(
                    x: .value("Date", selectedEntry.date),
                    y: .value("Weight", selectedEntry.kilograms)
                )
                .annotation(position: .top) {
                    Text("\(selectedEntry.kilograms, specifier: "%.1f") kg")
                        .font(.caption.bold())
                }
            }
        }
        .chartYScale(domain: .automatic(includesZero: false))
    }
}

拖动数据图表功能需要 iOS 17 或更高版本。在 iOS 16 上,用户可以看到折线,但无法沿其拖动。

该方案假设每周体重变化为 0.5 kg。如需使用其他变化速率,请修改 weeklyChange。

5. 将数据图表与自定义元素匹配

在你的全局解析器中,添加一个 WeightPlanStore 属性。然后为 line_chart 类型和 weight_goal ID 返回图表视图。高亮行显示了需要添加或修改的内容。如果你的应用还没有全局解析器,可以直接复制完整代码:


// the weight plan that your shared code sends before the paywall flow opens
@MainActor
final class WeightPlanStore {
    var plan: WeightPlan?
}

struct CustomElementsResolver: AdaptyUICustomElementsResolver {
    let weightPlanStore: WeightPlanStore

    func view(
        forType type: String,
        id: String,
        context: AdaptyUICustomElementContext
    ) -> AnyView? {
        switch type {
        case "line_chart" where id == "weight_goal":
            guard #available(iOS 16.0, *), let plan = weightPlanStore.plan else {
                return nil // no weight plan: show the fallback
            }
            return AnyView(WeightGoalChart(entries: plan.entries))
        // the other cases of your resolver
        default:
            return nil
        }
    }
}

在您的共享代码将当前体重和目标体重发送到原生代码之前,解析器不会返回任何视图,用户将看到备用内容。

6. 在共享代码中发送当前体重和目标体重

在应用启动时设置解析器,并从共享代码中填充 store。共享代码无法调用你的 Swift 代码或 MainApplication 类。要填充 store,需在共享代码中声明一个接口,然后在各平台的 WeightPlanStore 类中实现它。

在 commonMain 中,声明该接口以及一个持有当前平台 store 的对象:

// the weight plan store of each platform implements this interface
interface WeightPlanReceiver {
    fun setWeights(currentWeight: Double, goalWeight: Double)
}

object WeightPlanBridge {
    // the platform code sets the receiver at app launch
    var receiver: WeightPlanReceiver? = null
}

为每个平台实现该接口:

Make WeightPlanStore conform to the WeightPlanReceiver protocol from your shared framework, such as ComposeApp. The highlighted lines show what to add:


// the weight plan that your shared code sends before the paywall flow opens
@MainActor
final class WeightPlanStore: WeightPlanReceiver {
    var plan: WeightPlan?

    // your shared code can call this method on any thread
    nonisolated func setWeights(currentWeight: Double, goalWeight: Double) {
        // the resolver reads the weight plan on the main thread
        Task { @MainActor in
            self.plan = WeightPlan(currentWeight: currentWeight, goalWeight: goalWeight)
        }
    }
}

在 iOSApp.swift 中,向 AppDelegate 类添加一个体重计划属性。在 application(_:didFinishLaunchingWithOptions:) 方法中设置 resolver 和 receiver。高亮行显示了需要添加的内容。保持 AppDelegate 类的其余部分不变:


class AppDelegate: UIResponder, UIApplicationDelegate {
    // the weight plan that your shared code sends
    let weightPlanStore = WeightPlanStore()

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

在您共享的代码中,在付费墙流程打开之前,将当前体重和目标体重发送到 store:


private val mainUiScope = MainScope()

fun showWeightPaywall(currentWeight: Double, goalWeight: Double) {
    mainUiScope.launch {
        // the native resolver builds the chart from the current and goal weight
        WeightPlanBridge.receiver?.setWeights(currentWeight, goalWeight)
        Adapty.getFlow("weight_paywall")
            .onSuccess { flow ->
                AdaptyUI.createFlowView(flow)
                    .onSuccess { view -> view.present() }
                    .onError { error ->
                        // handle the error
                    }
            }
            .onError { error ->
                // handle the error
            }
    }
}

7. 在设备上测试

流程与付费墙编辑工具无法运行你的应用代码,因此其画布只会显示备用内容。要预览数据图表:

  1. 发布这两个流程。若要查看最新发布版本而非缓存版本,请将设备注册为测试设备。
  2. 运行包含 resolver 的应用构建版本。在 iOS 上,请使用 iOS 17 或更高版本的设备。完成用户引导流程,输入当前体重和目标体重。验证数据图表的折线是否从当前体重开始,到目标体重结束。
  3. 在数据图表上拖动,验证手指所在周的预测体重是否显示在折线上方。

要测试备用方案,请对 line_chart 类型不返回任何视图,然后重新打开付费墙流程。

要了解为什么备用方案会代替数据图表出现,请参阅 Kotlin Multiplatform 指南中的在设备上测试部分。