ペイウォールにインタラクティブな体重目標チャートを表示する

C# コードでユーザーの現在体重と目標体重を収集し、ネイティブコードに送信します。チャートはアプリがカスタム要素としてネイティブビューでレンダリングします。iOS では Swift Charts を使用し、Android ではチャートライブラリを使わずに描画します。ユーザーがオンボーディングフローで現在体重と目標体重を入力すると、そのアプリのペイウォールフローに予測体重をチャートとして表示できます。

このレシピでは、iOSレシピとAndroidレシピのフローのセットアップとネイティブビューを再利用します。このレシピの各ステップでは、それらから何をコピーするか、そしてUnityプロジェクトで何を異なる方法で行うかを説明します。

始める前に

  • Adapty Unity SDK 4.4以降にアプリを更新してください。それ以前のSDKバージョンでは、すべてのカスタム要素にフォールバックコンテンツが表示されます。
  • 取得および表示フローのアプリ設定を行ってください。
  • Unity SDKでカスタム要素を表示するの手順に従って、カスタム要素用のアプリ設定を行ってください。このレシピでは、そのガイドのC#とJavaのCustomElementsクラスにコードを追加します。
  • iOSでは、チャート上のドラッグ操作にiOS 17以降が必要です。iOS 16では折れ線は表示されますが、ドラッグ操作はできません。

2つの別々のフローを作成します。1つはオンボーディング用、もう1つはペイウォール用です。それぞれをプレースメントに追加してください。このレシピのコードは、ID weight_paywall のプレースメントからペイウォールフローを取得します。

1. オンボーディングフローとペイウォールフローを設定する

iOSレシピのステップ1と2と同様に、両方のフローを設定します:オンボーディングフローに2つの Number 入力、ペイウォールフローにチャート用のカスタム要素を追加してください。

2. ネイティブコードを追加する

iOS と Android のレシピでは、ペイウォールフローにリゾルバーをアタッチします。Unity SDK にはひとつのフローに対するリゾルバーの API がありません。その代わり、アプリ全体のリゾルバーがストアからウェイトプランを読み取り、ペイウォールフローが開く前に C# コードがそのストアにデータを書き込みます。

iOS

Assets/Plugins/iOS にある Swift ファイルに、iOS レシピのステップ 4 で作成したウェイトプランとチャートビューを追加します。次に、ウェイトプランのストア、ストアを読み込むリゾルバー、そして C# コードから呼び出す 2 つの関数を追加します。RegisterCustomElements は起動時にリゾルバーを設定し、SetWeightPlan はストアにデータを書き込みます。


// 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

WeightPlan、WeightEntry、WeightGoalChartView の各クラスを、Android レシピのステップ 4 の Java タブからコピーしてください。各クラスを 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 ガイドの「デバイスでテストする」セクションの手順に従ってください。