按照此方案,将用户进度以 Lottie 动画的形式展示——例如,用一个逐渐填充的圆环来表示用户的每日连续打卡天数。你的应用会在自定义元素中以原生 Lottie 视图渲染该动画。
开始之前
- 将应用更新至 Adapty React Native SDK 4.4 或更高版本。早期 SDK 版本会为每个自定义元素显示备用内容。
- 配置应用以获取和展示流程。
- 按照 React Native 指南为自定义元素配置应用的原生代码。
- 在 iOS 上,通过 Swift Package Manager 将 Lottie 添加到 Xcode 中的应用 target,地址为
https://github.com/airbnb/lottie-spm.git。如果应用已使用 lottie-react-native,可跳过此步骤:该包已将 Lottie 添加到应用中。
- 在 Android 上,在应用模块中配置 Jetpack Compose。本示例中的动画视图是一个 composable 组件。通过 Gradle 添加 Compose Foundation 和适用于 Jetpack Compose 的 Lottie,依赖分别来自
androidx.compose.foundation:foundation 和 com.airbnb.android:lottie-compose。
准备一个 .json 格式的 Lottie 动画,或下载示例文件 streak_ring.json。应用会从头播放动画,并按进度比例停止,例如进度为 50% 时停在中间位置。为了准确呈现进度,动画需要满足以下要求:
- 第一帧不显示任何进度,最后一帧显示完整进度。
- 匀速播放,不带缓动效果。如果动画开始时较慢、后来加速,则播放到一半时显示的进度会少于 50%。
1. 将自定义元素添加到屏幕
在流程与付费墙编辑工具中,向流程屏幕添加自定义元素,并为动画进行如下配置:
- 类型:
lottie_animation。
- ID:
streak_ring。在本示例中,ID 同时也是动画文件的名称。
- 高度:保持默认的固定高度。动画会自动缩放以适应自定义元素的尺寸。
在自定义元素内部,添加一个包含圆环静态图片的图片。当用户使用的应用版本不支持播放动画时,该图片将作为备用内容显示。
2. 将动画文件添加到应用
原生代码从 iOS 和 Android 项目中读取动画文件,而非从 JavaScript 代码的资源目录中读取:
- iOS:在 Xcode 中将文件添加到应用目标。
- Android:将文件放入
android/app/src/main/assets,即 Android 应用模块的 assets 文件夹。请将文件放在该文件夹的根目录下,不要放入子文件夹。
去掉 .json 后缀的文件名必须与自定义元素的 ID 一致,例如 streak_ring 对应 streak_ring.json。
3. 创建动画视图
为连续打卡天数创建一个数据模型,以及一个用于播放动画的视图。当连续打卡天数发生变化时,应用更新模型;视图读取模型,因此页面打开时会显示当前的连续打卡天数:
// The streak that your app keeps up to date
@MainActor
final 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)) 将动画环从空填充至 progress 位置,播放一次。
// the streak that your app keeps up to date
class StreakStore {
val currentStreak = MutableStateFlow(0) // days in a row
}
@Composable
fun 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) 会将圆环从空状态填充到 progress 指定的位置。
4. 将动画与自定义元素匹配
在你的应用全局解析器中,为连胜模型添加一个属性。然后为 lottie_animation 类型和 streak_ring ID 返回动画视图。高亮行显示了需要添加或修改的内容。如果你的应用还没有全局解析器,请复制完整代码:
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
}
}
}
将 streak_ring case 放在其他所有 lottie_animation case 之前,因为 Swift 只会执行第一个匹配的 case。如果应用包中找不到对应 ID 的文件,解析器会返回 nil,用户将看到备用内容。
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
}
}
如果 assets 文件夹中没有对应 ID 的文件,resolver 会返回 null,用户将看到备用内容。如果你的 resolver 已经为每个动画文件返回了对应的视图,当 ID 不是 streak_ring 时,请返回该视图而非 null。这样,用户仍然可以看到其他 lottie_animation 自定义元素的动画效果。
创建包含连续打卡模型的 resolver,并在应用启动时将其设置为全局 resolver:
在 AppDelegate.swift 中,为连续天数模型添加一个属性,并在 application(_:didFinishLaunchingWithOptions:) 方法中设置解析器。高亮行显示了需要添加的内容。其余 AppDelegate 类保持不变:
@main
class 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
}
}
在 MainApplication.kt 中,为连续打卡模型添加一个属性,并在 onCreate 方法中设置解析器。高亮行为需要新增的内容,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. 从 JavaScript 代码发送连续打卡数
你的 JavaScript 代码负责维护连续打卡数,原生视图则从 streak 模型中读取它。若要更新模型,需通过 Turbo Native Module 将连续打卡数发送到原生代码。该模块包含一个 JavaScript 规范文件以及各平台的实现代码。
在项目根目录的 specs 文件夹中,创建模块的规范文件:
export interface Spec extends TurboModule {
setStreak(days: number): void;
}
export default TurboModuleRegistry.getEnforcing<Spec>('NativeStreakStore');
要生成规范的原生代码,请在 package.json 中添加 codegenConfig。将 com.example.app 替换为你的 Android 应用的包名,分别在 package.json 和模块的 Kotlin 实现中修改。如果 package.json 中已存在 codegenConfig,只需将 NativeStreakStore 添加到 modulesProvider 对象中:
"codegenConfig": {
"name": "AppSpecs",
"type": "modules",
"jsSrcsDir": "specs",
"android": {
"javaPackageName": "com.example.app.specs"
},
"ios": {
"modulesProvider": {
"NativeStreakStore": "RCTNativeStreakStore"
}
}
}
为每个平台实现该模块:
在 Xcode 的应用程序目标中,创建一个 Objective-C++ 模块。它通过 NotificationCenter 将连续天数数据发送到你的 Swift 代码:
#import <AppSpecs/AppSpecs.h>
@interface RCTNativeStreakStore : NSObject <NativeStreakStoreSpec>
@end
#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
要在每次更新连续签到模型时保持同步,请在 AppDelegate 类中监听 NotificationCenter。在 application(_:didFinishLaunchingWithOptions:) 方法中,于 AdaptyUI.setCustomElementsResolver 调用之后添加观察者:
// the streak that your JavaScript code sends through the native module
NotificationCenter.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 }
}
要生成规范的原生代码,请在 ios 文件夹中运行 pod install。
Create the module, and a package that registers it with React Native:
package com.example.app
class 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,
)
)
}
}
在 MainApplication.kt 中,将 NativeStreakStorePackage 添加到 packages 列表:
PackageList(this).packages.apply {
add(NativeStreakStorePackage())
}
在 JavaScript 代码中,于应用启动时以及每次连续天数变化时发送数据:
// call at app launch, and each time the streak changes
export function sendStreak(days: number) {
NativeStreakStore.setStreak(days);
}
6. 在设备上测试
流程与付费墙编辑工具无法运行您的应用代码,因此画布上只显示备用内容。如需预览动画:
- 发布流程。若要查看最新发布版本而非缓存版本,请将设备注册为测试设备。
- 运行包含 resolver 的应用构建版本。将连续天数设为 0 天,打开界面,验证圆环保持空心状态。分别设为 4 天和 7 天后重复操作,验证圆环是否填充至对应值。
如需测试备用内容,请从构建版本中移除动画文件,然后再次打开界面。
如需了解为何显示备用内容而非动画,请参阅 React Native 指南中在设备上测试部分的说明。