按照此方案,在付费墙流程中以数据图表形式展示每位用户的预计体重变化。用户在用户引导流程中输入当前体重和目标体重,你的应用收集这两个数值。数据图表展示用户在使用你的应用后每周可预期的进度,从当前体重到目标体重。你的应用以原生视图的形式在自定义元素中渲染数据图表。iOS 使用 Swift Charts,Android 则不依赖图表库直接绘制。
开始之前
- 将您的应用更新至 Adapty React Native SDK 4.4 或更高版本。早期 SDK 版本会为每个自定义元素显示备用内容。
- 设置您的应用以获取和展示流程。
- 按照 React Native 指南为自定义元素配置应用的原生代码。
- 在 iOS 上,沿数据图表拖动功能需要 iOS 17 或更高版本。在 iOS 16 上,用户可以看到线条,但无法沿其拖动。
- 在 Android 上,请在您的应用模块中配置 Jetpack Compose。本示例中的数据图表是一个可组合项。通过 Gradle 将 Compose Foundation 添加到您的应用,依赖为
androidx.compose.foundation:foundation。
创建两个独立的流程——一个用于用户引导,一个用于付费墙。将每个流程添加到对应的版位。本示例代码从 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,即打开带数据图表的付费墙流程的函数。
以下函数返回用户引导流程的 onAnalytics 和 onDisappeared 处理器:
// the event handlers of the onboarding flow view
export function weightOnboardingHandlers(): Partial<FlowEventHandlers> {
const enteredWeights: Record<string, string> = {};
let reachedLastScreen = false;
return {
onAnalytics(name, params) {
if (name === 'flow_screen_showed' && params.is_last_screen === true) {
reachedLastScreen = true;
} else if (
name === 'flow_user_input' &&
typeof params.element_id === 'string' &&
typeof params.value === 'string'
) {
enteredWeights[params.element_id] = params.value;
}
return false; // keep the flow open
},
onDisappeared() {
// number inputs send their values as strings
const currentWeight = Number.parseFloat(enteredWeights.weight ?? '');
const goalWeight = Number.parseFloat(enteredWeights.goal_weight ?? '');
if (reachedLastScreen && !Number.isNaN(currentWeight) && !Number.isNaN(goalWeight)) {
showWeightPaywall(currentWeight, goalWeight);
}
return false;
},
};
}
在展示用户引导流程之前,将处理程序传递给其视图:
const view = await createFlowView(flow);
view.setEventHandlers(weightOnboardingHandlers());
await view.present();
如果你的应用已经为用户引导流程设置了 onAnalytics 或 onDisappeared,请将 weightOnboardingHandlers 的代码添加到你的处理程序中。传递给 setEventHandlers 的每个处理程序都会替换之前同名的处理程序。
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 上,用户可以看到该线条,但无法沿线拖动。
class WeightPlan(currentWeight: Double, goalWeight: Double) {
// one entry per week, from the current weight to the goal weight
val entries: List<WeightEntry> = run {
val weeklyChange = 0.5 // kg per week
val start = System.currentTimeMillis()
val weekMillis = 7L * 24 * 60 * 60 * 1000
val weeks = ceil(abs(goalWeight - currentWeight) / weeklyChange).toInt()
val step = if (goalWeight < currentWeight) -weeklyChange else weeklyChange
(0..weeks).map { week ->
val kilograms = if (week == weeks) goalWeight else currentWeight + step * week
WeightEntry(Date(start + week * weekMillis), kilograms)
}
}
}
data class WeightEntry(val date: Date, val kilograms: Double)
@Composable
fun WeightGoalChart(entries: List<WeightEntry>) {
// the week under the finger, or null when the user isn't dragging
var selectedIndex by remember { mutableStateOf<Int?>(null) }
val textMeasurer = rememberTextMeasurer()
val dateFormat = remember { DateFormat.getDateInstance(DateFormat.MEDIUM) }
val color = Color(0xFFAF52DE)
val textStyle = TextStyle(color = Color.Gray, fontSize = 12.sp)
val minKg = entries.minOf { it.kilograms }
val kgRange = (entries.maxOf { it.kilograms } - minKg).coerceAtLeast(1.0)
Canvas(
Modifier
.fillMaxSize()
.pointerInput(entries) {
// horizontal drags select a week; vertical drags scroll the screen
detectHorizontalDragGestures(
onDragEnd = { selectedIndex = null },
onDragCancel = { selectedIndex = null },
) { change, _ ->
val index = (change.position.x / size.width * entries.lastIndex).roundToInt()
selectedIndex = index.coerceIn(0, entries.lastIndex)
}
}
) {
val startDate = textMeasurer.measure(dateFormat.format(entries.first().date), textStyle)
val endDate = textMeasurer.measure(dateFormat.format(entries.last().date), textStyle)
val dateY = size.height - startDate.size.height
val top = 24.dp.toPx() // room for the projected weight above the line
val bottom = dateY - 8.dp.toPx()
fun pointOf(index: Int) = Offset(
x = size.width * index / entries.lastIndex.coerceAtLeast(1),
y = bottom - ((entries[index].kilograms - minKg) / kgRange * (bottom - top)).toFloat(),
)
// the line from the current weight to the goal weight
for (index in 1..entries.lastIndex) {
drawLine(color, pointOf(index - 1), pointOf(index), strokeWidth = 2.dp.toPx())
}
// the dates of the first and the last week
drawText(startDate, topLeft = Offset(0f, dateY))
drawText(endDate, topLeft = Offset(size.width - endDate.size.width, dateY))
// the selected week: a point, and the projected weight above it
selectedIndex?.let { index ->
val point = pointOf(index)
drawCircle(color, radius = 5.dp.toPx(), center = point)
val weight = String.format(Locale.getDefault(), "%.1f kg", entries[index].kilograms)
val label = textMeasurer.measure(weight, textStyle.copy(color = color))
val x = (point.x - label.size.width / 2)
.coerceAtMost(size.width - label.size.width)
.coerceAtLeast(0f)
drawText(label, topLeft = Offset(x, point.y - label.size.height - 8.dp.toPx()))
}
}
}
该方案假设每周体重变化为 0.5 kg。如需使用其他变化速率,请修改 weeklyChange。
5. 将数据图表与自定义元素匹配
在你的全局解析器中,添加一个 WeightPlanStore 属性。然后为 line_chart 类型和 weight_goal ID 返回数据图表视图。高亮行显示了需要添加或修改的内容。如果你的应用还没有全局解析器,请复制完整代码:
// the weight plan that your JavaScript 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
}
}
}
// the weight plan that your JavaScript code sends before the paywall flow opens
class WeightPlanStore {
var plan: WeightPlan? = null
}
class CustomElementsResolver(
private val weightPlanStore: WeightPlanStore,
) : AdaptyCustomElementsResolver {
override fun resolve(type: String, id: String): AdaptyCustomElementContent? =
when (type) {
"line_chart" -> {
val plan = weightPlanStore.plan
if (id == "weight_goal" && plan != null) {
AdaptyCustomElementContent.compose { WeightGoalChart(plan.entries) }
} else {
null // no weight plan: show the fallback
}
}
// the other Types of your resolver
else -> null
}
}
在您的 JavaScript 代码将权重发送到原生代码之前,解析器不会返回任何视图,用户将看到备用付费墙。
6. 从 JavaScript 代码发送权重
在应用启动时设置解析器,并通过 Turbo Native Module 从 JavaScript 代码填充存储。该模块包含一个 JavaScript 规范和各平台对应的实现。
在项目根目录下的 specs 文件夹中,创建模块规范:
export interface Spec extends TurboModule {
setWeights(currentWeight: number, goalWeight: number): void;
}
export default TurboModuleRegistry.getEnforcing<Spec>('NativeWeightPlanStore');
要生成规范的原生代码,请在 package.json 中添加 codegenConfig。将 com.example.app 替换为你的 Android 应用包名,需在 package.json 和模块的 Kotlin 实现中同步修改。如果 package.json 中已有 codegenConfig,则只需将 NativeWeightPlanStore 添加到 modulesProvider 对象中:
"codegenConfig": {
"name": "AppSpecs",
"type": "modules",
"jsSrcsDir": "specs",
"android": {
"javaPackageName": "com.example.app.specs"
},
"ios": {
"modulesProvider": {
"NativeWeightPlanStore": "RCTNativeWeightPlanStore"
}
}
}
为每个平台实现该模块:
在 Xcode 的 app target 中,创建一个 Objective-C++ 模块。它通过 NotificationCenter 将权重数据传递给你的 Swift 代码:
#import <AppSpecs/AppSpecs.h>
@interface RCTNativeWeightPlanStore : NSObject <NativeWeightPlanStoreSpec>
@end
#import "RCTNativeWeightPlanStore.h"
@implementation RCTNativeWeightPlanStore
+ (NSString *)moduleName {
return @"NativeWeightPlanStore";
}
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
(const facebook::react::ObjCTurboModule::InitParams &)params {
return std::make_shared<facebook::react::NativeWeightPlanStoreSpecJSI>(params);
}
- (void)setWeights:(double)currentWeight goalWeight:(double)goalWeight {
// the AppDelegate updates the weight plan when it receives this notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"WeightsDidChange"
object:nil
userInfo:@{@"current": @(currentWeight),
@"goal": @(goalWeight)}];
}
@end
在 AppDelegate.swift 中,为体重计划添加一个属性。在 application(_:didFinishLaunchingWithOptions:) 方法中设置 resolver,并监听 NotificationCenter 以在每次接收到新的体重数据对时更新体重计划。高亮行为新增内容,AppDelegate 类的其余部分保持不变:
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
// the weight plan that your JavaScript code sends
let weightPlanStore = WeightPlanStore()
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore: weightPlanStore))
// the weights that your JavaScript code sends through the native module
NotificationCenter.default.addObserver(
forName: Notification.Name("WeightsDidChange"),
object: nil,
queue: .main
) { [weightPlanStore] notification in
guard let currentWeight = notification.userInfo?["current"] as? Double,
let goalWeight = notification.userInfo?["goal"] as? Double
else { return }
MainActor.assumeIsolated {
weightPlanStore.plan = WeightPlan(currentWeight: currentWeight, goalWeight: goalWeight)
}
}
// the rest of your launch code
return true
}
}
要生成规范的原生代码,请在 ios 文件夹中运行 pod install。
创建模块,以及将其注册到 React Native 的包:
package com.example.app
class NativeWeightPlanStoreModule(reactContext: ReactApplicationContext) :
NativeWeightPlanStoreSpec(reactContext) {
override fun getName() = NAME
override fun setWeights(currentWeight: Double, goalWeight: Double) {
val app = reactApplicationContext.applicationContext as MainApplication
// the resolver reads the weight plan on the main thread
UiThreadUtil.runOnUiThread {
app.weightPlanStore.plan = WeightPlan(currentWeight, goalWeight)
}
}
companion object {
const val NAME = "NativeWeightPlanStore"
}
}
class NativeWeightPlanStorePackage : BaseReactPackage() {
override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? =
if (name == NativeWeightPlanStoreModule.NAME) NativeWeightPlanStoreModule(reactContext) else null
override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {
mapOf(
NativeWeightPlanStoreModule.NAME to ReactModuleInfo(
name = NativeWeightPlanStoreModule.NAME,
className = NativeWeightPlanStoreModule.NAME,
canOverrideExistingModule = false,
needsEagerInit = false,
isCxxModule = false,
isTurboModule = true,
)
)
}
}
在 MainApplication.kt 中,添加一个体重计划属性,并在 onCreate 方法中设置解析器。高亮行显示需要添加的内容。保持 MainApplication 类的其余部分不变:
class MainApplication : Application(), ReactApplication {
// the weight plan that your JavaScript code sends
val weightPlanStore = WeightPlanStore()
// the other members of your MainApplication class
override fun onCreate() {
super.onCreate()
AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore))
// the rest of your onCreate code
}
}
在 MainApplication.kt 中,将 NativeWeightPlanStorePackage 添加到包列表中:
PackageList(this).packages.apply {
add(NativeWeightPlanStorePackage())
}
在 JavaScript 代码中,在付费墙流程打开之前将权重发送到 store:
export async function showWeightPaywall(currentWeight: number, goalWeight: number) {
try {
// the native resolver builds the chart from these weights
NativeWeightPlanStore.setWeights(currentWeight, goalWeight);
const flow = await adapty.getFlow('weight_paywall');
const view = await createFlowView(flow);
await view.present();
} catch (error) {
// handle the error
}
}
7. 在设备上测试
Flow & Paywall Builder 无法运行你的应用代码,因此其画布仅显示备用内容。要预览数据图表:
- 发布两个流程。要查看最新发布的版本而非缓存版本,请将设备注册为测试设备。
- 运行包含解析器的应用构建版本。在 iOS 上,请使用 iOS 17 或更高版本的设备。完成包含当前体重和目标体重的用户引导流程,验证数据图表的折线是否从当前体重开始,到目标体重结束。
- 在数据图表上拖动,验证手指所在周的预测体重是否显示在折线上方。
要测试备用方案,请为 line_chart 类型不返回任何视图,然后再次打开付费墙流程。
要了解为何显示备用方案而非数据图表,请参阅 React Native 指南中在设备上测试部分的说明。