Các skill bao gồm tích hợp SDK, xây dựng flow và paywall, kiểm tra trước khi phát hành, di chuyển placement và nhiều hơn nữa. Mô tả công việc bằng ngôn ngữ thường ngày và agent sẽ chọn skill phù hợp.
Làm theo hướng dẫn này để hiển thị tiến trình của người dùng dưới dạng animation Lottie — ví dụ: một vòng tròn tô dần để hiển thị chuỗi ngày liên tiếp. Ứng dụng của bạn sẽ render animation dưới dạng native Lottie view trong một custom element.
Trước khi bắt đầu
Cập nhật ứng dụng lên Adapty React Native SDK 4.4 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 phần tử tùy chỉnh.
Thiết lập native code trong ứng dụng cho các phần tử tùy chỉnh, theo hướng dẫn React Native.
Trên iOS, thêm Lottie vào app target trong Xcode bằng Swift Package Manager, từ https://github.com/airbnb/lottie-spm.git. Nếu ứng dụng đã dùng lottie-react-native, bỏ qua bước này: package đó đã tích hợp sẵn Lottie.
Trên Android, thiết lập Jetpack Compose trong app module. Animation view trong recipe này là một composable. Thêm Compose Foundation và Lottie cho Jetpack Compose vào ứng dụng bằng Gradle, từ androidx.compose.foundation:foundation và com.airbnb.android:lottie-compose.
Chuẩn bị một animation Lottie ở định dạng .json, hoặc tải xuống file mẫu streak_ring.json. Ứng dụng phát animation từ đầu và dừng lại theo tỷ lệ tiến độ, chẳng hạn dừng ở giữa nếu tiến độ là 50%. Để hiển thị đúng tiến độ, animation cần đáp ứng:
Không có tiến độ ở frame đầu tiên, và tiến độ đầy đủ ở frame cuối cùng.
Tốc độ đều, không có easing. Nếu animation bắt đầu chậm rồi tăng tốc, nó sẽ hiển thị ít hơn một nửa tiến độ khi đã đi được nửa chừng.
ID: streak_ring. Trong hướng dẫn này, ID cũng là tên của file animation.
Height: Giữ nguyên chiều cao Fixed mặc định. Animation sẽ tự co giãn để vừa với phần tử tùy chỉnh.
Bên trong phần tử tùy chỉnh, thêm một Image với ảnh tĩnh của vòng tròn. Người dùng sẽ thấy nó như là nội dung dự phòng khi phiên bản ứng dụng của họ không phát được animation.
2. Thêm file animation vào ứng dụng
Code native của bạn đọc file animation từ dự án iOS và Android, không phải từ assets của code JavaScript:
iOS: Thêm file vào app target của bạn trong Xcode.
Android: Đặt file vào android/app/src/main/assets, thư mục assets của Android app module. Giữ file ở thư mục gốc, không đặt trong thư mục con.
Tên file không có .json phải khớp với ID của custom element, ví dụ streak_ring.json cho streak_ring.
3. Tạo animation view
Tạo một model cho streak và một view phát animation. Ứng dụng của bạn cập nhật model khi streak thay đổi. View đọc từ model, vì vậy vòng tròn sẽ hiển thị streak hiện tại khi màn hình mở ra:
// The streak that your app keeps up to date@MainActorfinal class StreakStore: ObservableObject { @Published var currentStreak = 0 // days in a row}struct StreakRingView: View { let animation: LottieAnimation @ObservedObject var streakStore: StreakStore // 7 days fill the ring: from 0 for an empty ring to 1 for a full one private var progress: AnimationProgressTime { min(AnimationProgressTime(streakStore.currentStreak) / 7, 1) } var body: some View { LottieView(animation: animation) .resizable() .playing(.fromProgress(0, toProgress: progress, loopMode: .playOnce)) }}
.playing(.fromProgress(0, toProgress: progress, loopMode: .playOnce)) lấp đầy vòng một lần, từ trống đến progress.
// the streak that your app keeps up to dateclass StreakStore { val currentStreak = MutableStateFlow(0) // days in a row}@Composablefun StreakRing(animationFile: String, streakStore: StreakStore) { val composition by rememberLottieComposition(LottieCompositionSpec.Asset(animationFile)) val streak by streakStore.currentStreak.collectAsState() // 7 days fill the ring: from 0 for an empty ring to 1 for a full one val progress = minOf(streak / 7f, 1f) LottieAnimation( composition = composition, modifier = Modifier.fillMaxSize(), // scale the animation to fit the custom element clipSpec = LottieClipSpec.Progress(0f, progress), )}
clipSpec = LottieClipSpec.Progress(0f, progress) điền vào vòng tròn một lần, từ trống đến progress.
4. Khớp animation 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 cho streak model. Sau đó trả về animation view cho Type lottie_animation và ID streak_ring. Các dòng được highlight 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:
struct CustomElementsResolver: AdaptyUICustomElementsResolver { let streakStore: StreakStore func view( forType type: String, id: String, context: AdaptyUICustomElementContext ) -> AnyView? { switch type { case "lottie_animation" where id == "streak_ring": guard let animation = LottieAnimation.named(id) else { return nil // no animation file: show the fallback } return AnyView(StreakRingView(animation: animation, streakStore: streakStore)) // the other cases of your resolver default: return nil } }}
Đặt case streak_ring trước bất kỳ case lottie_animation nào khác, vì Swift chỉ chạy case đầu tiên khớp. Nếu bundle ứng dụng không có file nào cho ID đó, resolver sẽ trả về nil và người dùng sẽ thấy fallback.
class CustomElementsResolver( context: Context, private val streakStore: StreakStore,) : AdaptyCustomElementsResolver { // the animation files in the assets folder, listed once private val animationFiles: Set<String> = try { context.assets.list("").orEmpty().toSet() } catch (e: IOException) { emptySet() // no list of files: every Lottie element shows the fallback } override fun resolve(type: String, id: String): AdaptyCustomElementContent? = when (type) { "lottie_animation" -> { // the ID names the animation file, such as streak_ring.json val file = "$id.json" when { file !in animationFiles -> null // no file for this ID: show the fallback id == "streak_ring" -> AdaptyCustomElementContent.compose { StreakRing(file, streakStore) } // the other animations of your resolver else -> null } } // the other Types of your resolver else -> null }}
Nếu thư mục assets không có file nào khớp với ID, resolver sẽ trả về null và người dùng sẽ thấy fallback. Nếu resolver của bạn đã trả về view cho mọi file animation, hãy trả về view đó thay vì null khi ID không phải là streak_ring. Như vậy, người dùng vẫn thấy được các animation từ những custom element lottie_animation khác.
Tạo resolver với streak model, rồi đặt nó làm resolver toàn ứng dụng khi khởi động:
Trong AppDelegate.swift, thêm một thuộc tính cho streak model, và đặt resolver 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:
@mainclass AppDelegate: UIResponder, UIApplicationDelegate { // the streak model that your app updates let streakStore = StreakStore() func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { AdaptyUI.setCustomElementsResolver(CustomElementsResolver(streakStore: streakStore)) // the rest of your launch code return true }}
Trong MainApplication.kt, thêm một thuộc tính cho model streak và đặt resolver trong phương thức onCreate. 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 MainApplication:
class MainApplication : Application(), ReactApplication { // the streak model that your app updates val streakStore = StreakStore() // the other members of your MainApplication class override fun onCreate() { super.onCreate() AdaptyUI.setCustomElementsResolver(CustomElementsResolver(this, streakStore)) // the rest of your onCreate code }}
5. Gửi streak từ mã JavaScript của bạn
Mã JavaScript của bạn lưu trữ streak, và các native view đọc dữ liệu đó từ streak model. Để cập nhật model, hãy gửi streak sang native code thông qua một Turbo Native Module. Module này có một JavaScript spec và một phần triển khai cho mỗi nền tảng.
Trong thư mục specs ở thư mục gốc của dự án, hãy tạo spec cho module:
Để tạo mã native cho spec, thêm codegenConfig vào package.json. Thay com.example.app bằng tên package của ứng dụng Android của bạn, trong package.json và trong phần triển khai Kotlin của module. Nếu package.json đã có codegenConfig, chỉ cần thêm NativeStreakStore vào object modulesProvider:
#import "RCTNativeStreakStore.h"@implementation RCTNativeStreakStore+ (NSString *)moduleName { return @"NativeStreakStore";}- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule: (const facebook::react::ObjCTurboModule::InitParams &)params { return std::make_shared<facebook::react::NativeStreakStoreSpecJSI>(params);}- (void)setStreak:(double)days { // the AppDelegate updates the streak model when it receives this notification [[NSNotificationCenter defaultCenter] postNotificationName:@"StreakDidChange" object:nil userInfo:@{@"days": @((NSInteger)days)}];}@end
Để cập nhật mô hình streak với mỗi streak mới, hãy quan sát NotificationCenter trong class AppDelegate của bạn. Trong phương thức application(_:didFinishLaunchingWithOptions:), thêm observer sau lệnh gọi AdaptyUI.setCustomElementsResolver:
// the streak that your JavaScript code sends through the native moduleNotificationCenter.default.addObserver( forName: Notification.Name("StreakDidChange"), object: nil, queue: .main) { [streakStore] notification in guard let days = notification.userInfo?["days"] as? Int else { return } MainActor.assumeIsolated { streakStore.currentStreak = days }}
Để tạo mã native từ spec, chạy pod install trong thư mục ios.
Create the module, and a package that registers it with React Native:
package com.example.appclass NativeStreakStoreModule(reactContext: ReactApplicationContext) : NativeStreakStoreSpec(reactContext) { override fun getName() = NAME override fun setStreak(days: Double) { val app = reactApplicationContext.applicationContext as MainApplication app.streakStore.currentStreak.value = days.toInt() } companion object { const val NAME = "NativeStreakStore" }}
class NativeStreakStorePackage : BaseReactPackage() { override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? = if (name == NativeStreakStoreModule.NAME) NativeStreakStoreModule(reactContext) else null override fun getReactModuleInfoProvider() = ReactModuleInfoProvider { mapOf( NativeStreakStoreModule.NAME to ReactModuleInfo( name = NativeStreakStoreModule.NAME, className = NativeStreakStoreModule.NAME, canOverrideExistingModule = false, needsEagerInit = false, isCxxModule = false, isTurboModule = true, ) ) }}
Trong MainApplication.kt, thêm NativeStreakStorePackage vào danh sách packages:
Trong code JavaScript, gửi streak khi khởi động app và mỗi khi streak thay đổi:
// call at app launch, and each time the streak changesexport function sendStreak(days: number) { NativeStreakStore.setStreak(days);}
6. Kiểm thử trên thiết bị
Flow & Paywall Builder không thể chạy code của ứng dụng, vì vậy canvas chỉ hiển thị fallback. Để xem trước animation:
Xuất bản flow. Để xem phiên bản đã xuất bản mới nhất thay vì phiên bản được lưu trong bộ nhớ đệm, hãy đăng ký thiết bị làm thiết bị thử nghiệm.
Chạy bản build của ứng dụng có chứa resolver. Đặt streak về 0 ngày, mở màn hình và xác nhận rằng vòng tròn vẫn trống. Lặp lại với 4 và 7 ngày, và xác nhận rằng vòng tròn được tô đầy đến từng giá trị tương ứng.
Để kiểm tra fallback, hãy xóa file animation khỏi bản build và mở lại màn hình.
Để tìm hiểu lý do tại sao paywall dự phòng hiển thị thay vì animation, hãy làm theo hướng dẫn trong phần Kiểm thử trên thiết bị của hướng dẫn React Native.