在付费墙中展示可交互的体重目标图表

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

这个示例复用了 iOS 示例 和 Android 示例 中的流程配置和原生视图。本示例的每个步骤都会说明需要从这两个示例中复制哪些内容,以及在 Unity 项目中需要做哪些不同的处理。

开始之前

  • 将您的应用更新至 Adapty Unity SDK 4.4 或更高版本。早期 SDK 版本会为每个自定义元素显示备用内容。
  • 设置您的应用以获取和展示流程。
  • 为自定义元素配置您的应用,具体参见使用 Unity SDK 展示自定义元素。本指南会在该教程的 C# 和 Java CustomElements 类中添加代码。
  • 在 iOS 上,沿数据图表拖动需要 iOS 17 或更高版本。在 iOS 16 上,用户可以看到该折线,但无法沿其拖动。

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

1. 设置用户引导流程和付费墙流程

按照 iOS 方案中第 1 步和第 2 步的方式设置两个流程:在用户引导流程中添加两个 Number 输入控件,在付费墙流程中添加一个用于显示图表的自定义元素。

2. 添加原生代码

iOS 和 Android 的方案是在付费墙流程中附加一个解析器。Unity SDK 没有针对单个流程解析器的 API。作为替代,你需要在应用全局解析器中从存储中读取权重计划,并在付费墙流程打开之前用 C# 代码填充该存储。

iOS

在 Assets/Plugins/iOS 的 Swift 文件中,添加来自 iOS 操作指南第 4 步的 weight plan 和 chart view。然后添加 weight plan 的 store、读取 store 的 resolver,以及供 C# 代码调用的两个函数。RegisterCustomElements 在启动时设置 resolver,SetWeightPlan 负责填充 store:


// the weight plan that your C# 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
        }
    }
}

@MainActor let weightPlanStore = WeightPlanStore()

// Called once from C# at launch, before any flow is created.
@_cdecl("RegisterCustomElements")
public func RegisterCustomElements() {
    Task { @MainActor in
        AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore: weightPlanStore))
    }
}

// Called from C# before the paywall flow opens.
@_cdecl("SetWeightPlan")
public func SetWeightPlan(_ currentWeight: Double, _ goalWeight: Double) {
    Task { @MainActor in
        weightPlanStore.plan = WeightPlan(currentWeight: currentWeight, goalWeight: goalWeight)
    }
}

Android

从 Android 教程步骤 4 的 Java 标签页中复制 WeightPlan、WeightEntry 和 WeightGoalChartView 类。将每个类保存到 Assets/Plugins/Android 目录下各自独立的文件中,例如 WeightPlan.java。每个文件开头使用 package com.example.app;,并添加该类所需的导入语句。

在 CustomElements.java 中,设置一个读取体重计划的解析器,并为 C# 代码添加 setWeightPlan 方法:

package com.example.app;


public final class CustomElements {
    // the weight plan that your C# code sends before the paywall flow opens
    private static volatile WeightPlan weightPlan;

    // Called once from C# at launch, before any flow is created.
    // This resolver doesn't use the context.
    public static void register(Context context) {
        AdaptyUI.setCustomElementsResolver((type, id) -> {
            WeightPlan plan = weightPlan;
            if ("line_chart".equals(type) && "weight_goal".equals(id) && plan != null) {
                return AdaptyCustomElementContent.view(
                        (viewContext, elementContext) -> new WeightGoalChartView(viewContext, plan.entries)
                );
            }
            return null; // no weight plan, or another custom element: show the fallback
        });
    }

    // Called from C# before the paywall flow opens.
    public static void setWeightPlan(double currentWeight, double goalWeight) {
        weightPlan = new WeightPlan(currentWeight, goalWeight);
    }
}

在您的 C# 代码发送当前体重和目标体重之前,解析器不会返回任何视图,用户看到的将是备用付费墙。

3. 从 C# 代码发送权重

在 C# 的 CustomElements 类中,添加一个 SendWeightPlan 方法,将两个权重传递给原生代码。高亮行显示了需要在 Unity 指南的类基础上新增的内容:

using UnityEngine;

public static class CustomElements
{
#if UNITY_IOS && !UNITY_EDITOR
    [System.Runtime.InteropServices.DllImport("__Internal")]
    private static extern void RegisterCustomElements();

    [System.Runtime.InteropServices.DllImport("__Internal")]
    private static extern void SetWeightPlan(double currentWeight, double goalWeight);
#endif

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    private static void Register()
    {
#if UNITY_IOS && !UNITY_EDITOR
        RegisterCustomElements();
#elif UNITY_ANDROID && !UNITY_EDITOR
        using (var player = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        using (var activity = player.GetStatic<AndroidJavaObject>("currentActivity"))
        using (var context = activity.Call<AndroidJavaObject>("getApplicationContext"))
        using (var resolver = new AndroidJavaClass("com.example.app.CustomElements"))
        {
            resolver.CallStatic("register", context);
        }
#endif
    }

    // call before the paywall flow opens
    public static void SendWeightPlan(double currentWeight, double goalWeight)
    {
#if UNITY_IOS && !UNITY_EDITOR
        SetWeightPlan(currentWeight, goalWeight);
#elif UNITY_ANDROID && !UNITY_EDITOR
        using (var customElements = new AndroidJavaClass("com.example.app.CustomElements"))
        {
            customElements.CallStatic("setWeightPlan", currentWeight, goalWeight);
        }
#endif
    }
}

通过 FlowViewDidReceiveAnalyticEvent 方法从用户引导流程中收集当前体重和目标体重,具体参见 向流程传递数据 中的 BMI 示例。FlowViewDidDisappear 仅在您的应用关闭用户引导流程后才会触发,因此请在 Close flow 操作时关闭流程,详见 关闭流程和付费墙。当用户在最后一个屏幕关闭用户引导流程后,将两个体重数据发送至您的原生代码,并打开付费墙流程:

public void FlowViewDidDisappear(AdaptyUIFlowView view) {
    // The listener receives events from every flow. Reset `bodyAnswers` and
    // `reachedLastScreen` whenever a flow disappears, so that the paywall
    // doesn't open again when the user closes it.
    var answers = new Dictionary<string, string>(bodyAnswers);
    var finished = reachedLastScreen;
    bodyAnswers.Clear();
    reachedLastScreen = false;

    // Number inputs send their values as strings.
    if (!finished) return;
    if (!answers.TryGetValue("weight", out var currentText)
        || !double.TryParse(currentText, out var currentWeight)) return;
    if (!answers.TryGetValue("goal_weight", out var goalText)
        || !double.TryParse(goalText, out var goalWeight)) return;

    // the resolver reads the weights when the paywall flow opens
    CustomElements.SendWeightPlan(currentWeight, goalWeight);
    ShowWeightPaywall();
}

private void ShowWeightPaywall() {
    Adapty.GetFlow("weight_paywall", (flow, flowError) => {
        if (flowError != null) {
            // handle the error
            return;
        }

        AdaptyUI.CreateFlowView(flow, new AdaptyUICreateFlowViewParameters(), (view, viewError) => {
            if (viewError != null) {
                // handle the error
                return;
            }

            view.Present((presentError) => {
                if (presentError != null) {
                    // handle the error
                }
            });
        });
    });
}

4. 在设备上测试

按照 iOS 和 Android 教程中第 6 步的方式测试两个流程。若要测试备用方案,可让解析器对 weight_goal ID 不返回任何视图,然后重新打开付费墙流程。

如需了解为何显示备用方案而非图表,请参阅 Unity 指南中在设备上测试部分的说明。