Hiển thị biểu đồ mục tiêu cân nặng tương tác trong paywall
Hãy làm theo hướng dẫn này để hiển thị biểu đồ cân nặng dự kiến của từng người dùng trong một paywall flow. Người dùng nhập cân nặng hiện tại và mục tiêu trong onboarding flow. Ứng dụng của bạn thu thập cả hai giá trị đó. Biểu đồ hiển thị tiến trình hàng tuần mà người dùng có thể kỳ vọng khi dùng ứng dụng của bạn, từ giá trị này đến giá trị kia. Ứng dụng của bạn render biểu đồ dưới dạng native view trong một custom element. Trên iOS, view sử dụng Swift Charts. Trên Android, view vẽ biểu đồ mà không cần thư viện chart.
Trước khi bắt đầu
- Cập nhật ứng dụng lên Adapty Kotlin Multiplatform SDK 4.4.0-beta.1 trở lên. Các phiên bản SDK cũ hơn sẽ hiển thị nội dung dự phòng cho mọi custom element.
- Thiết lập ứng dụng để tải và hiển thị flow.
- Thiết lập native code của ứng dụng cho các custom element, theo hướng dẫn Kotlin Multiplatform.
- Trên iOS, thao tác kéo dọc theo biểu đồ yêu cầu iOS 17 trở lên. Trên iOS 16, người dùng thấy đường kẻ nhưng không thể kéo dọc theo nó.
- Trên Android, thiết lập dự án Android của bạn, bao gồm Jetpack Compose. Biểu đồ trong recipe này là một composable. Nếu ứng dụng của bạn không sử dụng Compose Multiplatform, hãy thêm Compose Foundation vào dependencies của
androidMain, từandroidx.compose.foundation:foundation, không kèm phiên bản. Compose BOM củaio.adapty:android-uisẽ thiết lập phiên bản tương ứng.
Tạo hai flow riêng biệt — một cho onboarding và một cho paywall. Thêm mỗi flow vào một placement. Code trong hướng dẫn này lấy paywall flow từ placement có ID weight_paywall.
1. Hỏi cân nặng hiện tại và mục tiêu trong onboarding flow
Trong Flow & Paywall Builder, thêm hai input Number vào onboarding flow:
- Một input cho cân nặng hiện tại tính bằng kilogram, với Element ID là
weight. - Một input cho cân nặng mục tiêu tính bằng kilogram, với Element ID là
goal_weight.
Để app của bạn đọc được cân nặng theo cùng một cách ở mọi ngôn ngữ, hãy chọn Integer từ dropdown Format của cả hai input. Một input sẽ gửi giá trị của nó đến app dưới dạng văn bản, chính xác như người dùng nhập vào. Code trong recipe này đọc “70.5” và “70,5” khác nhau. Số nguyên không có dấu phân cách thập phân.
Để đảm bảo app nhận được cả hai giá trị, hãy kết thúc onboarding flow bằng một màn hình không có input nào. Trên màn hình đó, thêm một nút với hành động Close flow. Các input sẽ gửi giá trị của chúng khi mất focus hoặc khi người dùng chuyển sang màn hình khác.
2. Thêm phần tử tùy chỉnh vào màn hình paywall
Trong paywall flow, thêm một phần tử tùy chỉnh vào màn hình và cài đặt nó cho biểu đồ:
- Type:
line_chart. - ID:
weight_goal. - Height: Giữ nguyên chiều cao Fixed mặc định. Biểu đồ sẽ lấp đầy phần tử tùy chỉnh.
Đặt phần tử tùy chỉnh ngoài các container phản hồi thao tác chạm, chẳng hạn như carousel, để chỉ biểu đồ mới phản hồi khi người dùng kéo trên đó.
Bên trong phần tử tùy chỉnh, thêm một Image với biểu đồ cân nặng mẫu. Người dùng sẽ thấy nó là nội dung dự phòng khi phiên bản ứng dụng của họ không hiển thị được biểu đồ.
3. Lưu cân nặng hiện tại và mục tiêu trong ứng dụng
Thu thập cân nặng hiện tại và mục tiêu từ các sự kiện flow_user_input của onboarding flow, như hướng dẫn trong Xử lý dữ liệu từ flow. Để biết người dùng đã đến màn hình cuối cùng, hãy theo dõi sự kiện flow_screen_showed với is_last_screen được đặt thành true. Khi onboarding flow đóng lại sau màn hình đó, hãy truyền cân nặng hiện tại và mục tiêu vào showWeightPaywall — hàm mở paywall flow kèm biểu đồ.
Một observer nhận các sự kiện của cả hai flow. Hãy đăng ký nó với AdaptyUI.setFlowsEventsObserver trước khi bạn hiển thị onboarding flow. Observer mà bạn đăng ký sẽ thay thế observer trước đó: nếu ứng dụng của bạn đã đăng ký một observer, hãy thêm code của WeightFlowsObserver vào đó. Hàm showWeightPaywall đến từ bước 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. Tạo chart view
Tạo một model cho kế hoạch cân nặng và một view với biểu đồ. Kế hoạch có một mục nhập mỗi tuần, từ cân nặng hiện tại đến cân nặng mục tiêu. Khi người dùng kéo dọc theo biểu đồ, view sẽ đánh dấu tuần tại điểm chạm và hiển thị cân nặng dự kiến cho tuần đó:
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))
}
}Thao tác kéo trên biểu đồ yêu cầu iOS 17 trở lên. Trên iOS 16, người dùng thấy đường kẻ nhưng không thể kéo dọc theo nó.
Kế hoạch này giả định rằng cân nặng thay đổi 0,5 kg mỗi tuần. Để sử dụng tốc độ khác, hãy chỉnh sửa weeklyChange.
5. Khớp biểu đồ với phần tử tùy chỉnh
Trong resolver toàn ứng dụng của bạn, thêm một thuộc tính WeightPlanStore. Sau đó trả về view biểu đồ cho Type line_chart và ID weight_goal. Các dòng được tô sáng cho thấy những gì cần thêm hoặc thay đổi. Nếu ứng dụng của bạn chưa có resolver toàn ứng dụng, hãy sao chép toàn bộ đoạn code:
// 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
}
}
}Cho đến khi code dùng chung của bạn gửi cân nặng hiện tại và mục tiêu đến code native, resolver sẽ không trả về view nào và người dùng sẽ thấy paywall dự phòng.
6. Gửi cân nặng hiện tại và mục tiêu từ code dùng chung
Đặt resolver khi khởi động ứng dụng và điền dữ liệu vào store từ code dùng chung. Code dùng chung không thể gọi Swift code hay class MainApplication. Để điền vào store, hãy khai báo một interface trong code dùng chung và triển khai nó trong class WeightPlanStore của từng nền tảng.
Trong commonMain, khai báo interface và một object giữ store của nền tảng hiện tại:
// 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
}Triển khai interface cho từng nền tảng:
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)
}
}
}Trong iOSApp.swift, thêm một thuộc tính cho weight plan vào class AppDelegate của bạn. Đặt resolver và receiver trong phương thức application(_:didFinishLaunchingWithOptions:). Các dòng được tô sáng cho thấy những gì cần thêm. Giữ nguyên phần còn lại của class 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
}
}Trong code của bạn, hãy gửi cân nặng hiện tại và mục tiêu đến store trước khi flow paywall mở:
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. Kiểm tra trên thiết bị
Flow & Paywall Builder không thể chạy code ứng dụng của bạn, vì vậy canvas chỉ hiển thị fallback. Để xem trước biểu đồ:
- Xuất bản cả hai flow. Để xem phiên bản đã xuất bản mới nhất thay vì phiên bản được lưu trong cache, hãy đăng ký thiết bị làm thiết bị thử nghiệm.
- Chạy bản build ứng dụng có chứa resolver. Trên iOS, hãy dùng thiết bị chạy iOS 17 trở lên. Hoàn thành flow onboarding với cân nặng hiện tại và mục tiêu. Xác nhận rằng đường trên biểu đồ bắt đầu từ cân nặng hiện tại và kết thúc ở cân nặng mục tiêu.
- Kéo dọc theo biểu đồ và xác nhận rằng cân nặng dự kiến cho tuần mà bạn đang chạm vào hiển thị phía trên đường kẻ.
Để kiểm tra fallback, hãy không trả về view nào cho Type line_chart, rồi mở lại flow của paywall.
Để tìm hiểu lý do tại sao fallback xuất hiện thay vì biểu đồ, hãy làm theo hướng dẫn trong phần Kiểm tra trên thiết bị của hướng dẫn Kotlin Multiplatform.