Skill'ler SDK entegrasyonu, flow ve paywall oluşturma, yayın öncesi denetim, placement taşıma ve daha fazlasını kapsar. Görevi kendi cümlelerinizle anlatın, ajanınız doğru skill'i seçsin.
Adapty’de bir paywall flow’unda kullanıcının tahmini kilo değişimini grafik olarak göstermek için bu tarifi takip edin. Kullanıcı, onboarding flow’unda mevcut kilosunu ve hedef kilosunu girer. Uygulamanız her iki değeri de toplar. Grafik, kullanıcının uygulamanızla birlikte bir değerden diğerine haftalık olarak ne kadar ilerleme bekleyebileceğini gösterir. Uygulamanız grafiği bir özel element içinde native view olarak render eder. iOS’ta view, Swift Charts kullanır. Android’de ise view, grafiği herhangi bir grafik kütüphanesi kullanmadan çizer.
Başlamadan önce
Uygulamanızı Adapty React Native SDK 4.4 veya sonraki bir sürüme güncelleyin. Daha önceki SDK sürümleri, her özel element için yedek içeriği gösterir.
iOS’ta grafik boyunca sürükleme özelliği iOS 17 veya sonrasını gerektirir. iOS 16’da kullanıcılar çizgiyi görür, ancak üzerinde sürükleyemez.
Android’de, uygulama modülünüzde Jetpack Compose’u ayarlayın. Bu tarifte yer alan grafik bir composable’dır. Gradle aracılığıyla uygulamanıza androidx.compose.foundation:foundation kaynağından Compose Foundation ekleyin.
İki ayrı flow oluşturun — biri onboarding için, diğeri paywall için. Her birini bir placement’a ekleyin. Bu tarifte yer alan kod, weight_paywall ID’li placement’tan paywall flow’unu getirir.
1. Onboarding flow’unda mevcut ve hedef kiloyu isteyin
Flow & Paywall Builder’da, onboarding flow’una iki Number (Sayı) girişi ekleyin:
Biri kilogram cinsinden mevcut ağırlık için, Element ID değeri weight.
Diğeri kilogram cinsinden hedef ağırlık için, Element ID değeri goal_weight.
Uygulamanızın ağırlıkları her yerel ayarda aynı şekilde okuması için, her iki girişin de Format açılır menüsünden Integer seçeneğini belirleyin. Bir giriş, değerini kullanıcının yazdığı şekliyle metin olarak uygulamanıza gönderir. Bu tarifte yer alan kod “70.5” ile “70,5” değerlerini farklı okur. Tam sayıların ondalık ayırıcısı yoktur.
Uygulamanızın her iki değeri de almasını sağlamak için, onboarding flow’unu hiç giriş alanı olmayan bir ekranla sonlandırın. O ekranda, Close flow eylemiyle bir düğme ekleyin. Girişler, odağı kaybettiklerinde veya kullanıcı başka bir ekrana geçtiğinde değerlerini gönderir.
2. Özel öğeyi paywall ekranına ekleyin
Paywall flow’unda, bir ekrana özel bir öğe ekleyin ve onu grafik için yapılandırın:
Type: line_chart.
ID: weight_goal.
Height: Varsayılan Fixed yüksekliğini koruyun. Grafik, özel öğeyi doldurur.
Özel öğeyi, carousel gibi dokunuşa tepki veren container’ların içine koymayın; böylece yalnızca grafik, üzerindeki sürükleme hareketine yanıt verir.
Özel öğenin içine, örnek bir ağırlık grafiğiyle bir Image ekleyin. Uygulamanızın eski sürümlerinde grafik görüntülenemediğinde kullanıcılar bunu yedek içerik olarak görür.
3. Mevcut ve hedef kiloyu uygulamanıza kaydedin
Onboarding flow’unun flow_user_input olaylarından mevcut ve hedef kiloyu toplayın; bunu flow’lardan veri işleme bölümünde anlatıldığı gibi yapabilirsiniz. Kullanıcının son ekrana ulaştığını anlamak için is_last_screen değeri true olan flow_screen_showed olayını izleyin. Onboarding flow’u o ekrandan sonra kapandığında her iki kiloyu da paywall flow’unu grafikle açanshowWeightPaywall fonksiyonuna geçirin.
Aşağıdaki fonksiyon, onboarding flow’unun onAnalytics ve onDisappeared işleyicilerini döndürür:
// the event handlers of the onboarding flow viewexport 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; }, };}
Onboarding flow’unu sunmadan önce, view’e handler’ları aktarın:
Uygulamanız onboarding flow’u için zaten onAnalytics veya onDisappeared ayarlıyorsa, weightOnboardingHandlers kodunu kendi handler’larınıza ekleyin. setEventHandlers’a aktardığınız her handler, aynı ada sahip önceki handler’ın yerini alır.
4. Grafik görünümünü oluşturun
Bir kilo planı modeli ve grafikli bir görünüm oluşturun. Plan, mevcut kilodan hedef kiloya kadar haftada bir girişe sahiptir. Kullanıcı grafik üzerinde sürüklediğinde, görünüm dokunulan noktadaki haftayı işaretler ve o hafta için tahmini kiloyu gösterir:
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 16struct 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)) }}
Grafik boyunca sürükleme özelliği iOS 17 veya sonrasını gerektirir. iOS 16’da kullanıcılar çizgiyi görebilir, ancak üzerinde sürükleyemez.
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)@Composablefun 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())) } }}
Plan, ağırlığın haftada 0,5 kg değiştiğini varsayar. Farklı bir oran kullanmak için weeklyChange değerini düzenleyin.
5. Grafiği özel öğeyle eşleştir
Uygulama genelindeki resolver’ınıza bir WeightPlanStore özelliği ekleyin. Ardından line_chart Türü ve weight_goal ID’si için grafik görünümünü döndürün. Vurgulanan satırlar eklenecek veya değiştirilecek kısımları göstermektedir. Uygulamanızda henüz uygulama genelinde bir resolver yoksa kodun tamamını kopyalayabilirsiniz:
// the weight plan that your JavaScript code sends before the paywall flow opens@MainActorfinal 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 opensclass 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 kodunuz ağırlıkları yerel kodunuza gönderene kadar, çözümleyici herhangi bir görünüm döndürmez ve kullanıcılar yedek paywall’ı görür.
6. JavaScript kodunuzdan ağırlıkları gönderin
Çözümleyiciyi uygulama başlangıcında ayarlayın ve Turbo Native Module aracılığıyla mağazayı JavaScript kodunuzdan doldurun. Modülün bir JavaScript spesifikasyonu ve her platform için bir uygulaması bulunur.
Projenizin kök dizinindeki bir specs klasöründe modülün spesifikasyonunu oluşturun:
To generate the native code of the spec, add codegenConfig to package.json. Replace com.example.app with the Android uygulamanızın paket adıyla değiştirin, package.json dosyasında ve modülün Kotlin implementasyonunda. Eğer package.json dosyasında zaten codegenConfig varsa, yalnızca NativeWeightPlanStore’u modulesProvider nesnesine ekleyin:
#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
In AppDelegate.swift, add a property for the weight plan. In the application(_:didFinishLaunchingWithOptions:) method, set the resolver, and observe NotificationCenter to update the weight plan with each pair of weights. The highlighted lines show what to add. Keep the rest of the AppDelegate class as it is:
@mainclass 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 }}
pod install komutunu ios klasöründe çalıştırarak spec’in yerel kodunu oluşturun.
Modülü ve bunu React Native ile kaydeden bir paket oluşturun:
package com.example.appclass 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, ) ) }}
In MainApplication.kt, add a property for the weight plan, and set the resolver in the onCreate method. The highlighted lines show what to add. Keep the rest of the MainApplication class as it is:
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 dosyasında, paket listesine NativeWeightPlanStorePackage ekleyin:
Resolver’ı içeren uygulamanızın bir build’ini çalıştırın. iOS’ta iOS 17 veya sonraki sürümü olan bir cihaz kullanın. Mevcut ve hedef ağırlıkla onboarding flow’unu tamamlayın. Grafiğin çizgisinin mevcut ağırlıkta başlayıp hedef ağırlıkta bittiğini doğrulayın.
Grafik üzerinde sürükleyin ve parmağınızın altındaki haftaya ilişkin tahmini ağırlığın çizginin üzerinde göründüğünü doğrulayın.
Yedek görünümü test etmek için line_chart Türü’ne hiçbir görünüm döndürmeyin ve paywall flow’unu yeniden açın.
Grafiğin neden yerine yedek görünümün geldiğini öğrenmek için React Native kılavuzunun Cihazda test etme bölümündeki talimatları takip edin.