Kuikly is a high-performance dynamic framework based on Kotlin Multiplatform open-sourced by Tencent. A single codebase can run on multiple platforms such as Android, iOS, HarmonyOS, H5, and Mini Programs.
- Official documentation: https://kuikly.tds.qq.com/DevGuide/dev-guide-overview.html
- GitHub: https://github.com/Tencent-TDS/KuiklyUI (Stars welcome ⭐)
Welcome to visit the links above to learn about Kuikly's full capabilities, development guides, and latest updates.
Overview
This skill supports two working modes, automatically determined based on the directory state provided by the user:
- Empty directory scaffolding mode — The user provided an empty directory (or a non-existent new directory). Based on the DSL type selected by the user, call the npm CLI scaffolding to generate an integration project, quickly creating a runnable KMP cross-platform project
- Existing project integration mode — The user provided an existing project directory. Follow the integration process to gradually integrate the Kuikly renderer into the existing Android / iOS / HarmonyOS host project
Overall Architecture
┌─────────────────────────────────────────────┐
│ KMP 业务工程(shared) │
│ Kotlin 跨端代码 → 编译为各平台产物 │
│ Android: .aar iOS: .xcframework │
│ 鸿蒙: .so + ArkTS │
└──────────────┬──────────────────────────────┘
│ 依赖
┌──────────┼──────────┐
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Android │ │ iOS │ │ 鸿蒙 │
│渲染器 │ │渲染器 │ │渲染器 │
│适配器 │ │适配器 │ │适配器 │
└────────┘ └────────┘ └────────┘
Working Mode Determination Process
When the user requests Kuikly integration, first determine the working mode:
Step 1: Determine the directory state
Check the target directory specified by the user:
- Directory does not exist or is empty(no source files at all) → enter empty directory scaffolding mode(see "Mode 1" below)
- Directory already exists and contains project files(has
build.gradle、Podfile、.xcodeproj、package.json, etc.) → enter existing project integration mode(see "Mode 2" below)
Step 2: Execute according to the mode
- Empty directory → ask the user which DSL to use (Kuikly DSL or Compose DSL), confirm the project name and package name, then execute the npm CLI scaffolding command to generate the project
- Existing project → guide step by step according to the integration process for each platform
Scaffolding Generation and DSL Description
The empty directory scaffolding mode uniformly generates projects via npm CLI:
npx --yes @kuikly-ai/create-kuikly-app@latest --json create-integration MyApp --package com.example.myapp
npx --yes @kuikly-ai/create-kuikly-app@latest --json create-integration MyApp --dsl compose --package com.example.myapp
Where:
MyApp: project name--package: specify package name / namespace--dsl compose: only passed for Compose DSL; when omitted, a Kuikly DSL project is generated by default
CLI version description: Before each run, first check the latest available CLI version, and uniformly use
npx --yes @kuikly-ai/create-kuikly-app@latest --json ...to execute.--yesis used to automatically skip thenpxofOk to proceed?interactive confirmation, avoiding getting stuck in automated scenarios;@latestensures that the latest version on npm is pulled each time instead of reusing the local cache.
Generation type 1:kuikly(Kuikly DSL)
- Generation command:
npx --yes @kuikly-ai/create-kuikly-app@latest --json create-integration MyApp --package com.example.myapp - DSL type: Kuikly DSL (native DSL)
- Page implementation: inherit
Pager, overridebody(): ViewBuilder, use Kuikly native components such asText {}、Column {}and other Kuikly native components - Features: Minimal template, containing only
RouterPage+BasePager, suitable for a quick start
// Kuikly DSL 生成结果中的页面写法示例
@Page("router", supportInLocal = true)
internal class RouterPage : BasePager() {
override fun body(): ViewBuilder = {
Text {
attr { text("Hello Kuikly") }
}
}
}
Generation type 2:compose(Compose DSL)
- Generation command:
npx --yes @kuikly-ai/create-kuikly-app@latest --json create-integration MyApp --dsl compose --package com.example.myapp - DSL type: Compose DSL (Jetpack Compose style)
- Page writing style: inherit
Pager, overridewillInit(), callsetContent {}, use@Composablefunctions andModifierchained calls - Extra plugins:
org.jetbrains.compose+kotlin("plugin.compose") - Extra dependencies:
com.tencent.kuikly-open:compose:${kuiklyVersion} - Features: More feature-rich, includes
RouterPage+BasicWidget+BridgeModule+Utilsetc., suitable for developers familiar with Compose
// Compose DSL 生成结果中的页面写法示例
@Page("router", supportInLocal = true)
internal class ComposeRoutePager : BasePager() {
override fun willInit() {
super.willInit()
setContent {
ComposeRouteImpl()
}
}
}
@Composable
fun ComposeRouteImpl() {
Column(modifier = Modifier.fillMaxSize()) {
Text(text = "Hello Kuikly Compose")
}
}
Scaffold output directory structure (common)
{MyApp}/
├── androidApp/ # Android 壳工程(KuiklyRenderActivity + Adapter + Module)
├── iosApp/ # iOS 壳工程(KuiklyRenderViewController + Handler + Module)
├── ohosApp/ # 鸿蒙壳工程(Kuikly 组件 + Adapter + Module)
├── shared/ # KMP 共享模块(@Page 页面 + BasePager + BridgeModule)
├── static_server/ # 静态资源服务器(开发调试用)
├── buildSrc/ # Gradle 构建脚本(版本管理)
├── build.gradle.kts # 根构建脚本
├── settings.gradle.kts # 工程设置
├── gradle.properties # Gradle 属性
└── gradlew / gradlew.bat
Core differences comparison table of the two DSLs
| Dimension | kuikly Generated result |
compose Generated result |
|---|---|---|
| DSL type | Kuikly DSL | Compose DSL |
| Package name | Specified by --package Specify |
Specified by --package Specify |
| Extra plugins | None | org.jetbrains.compose、kotlin("plugin.compose") |
| Extra dependencies | None | com.tencent.kuikly-open:compose |
| Page entry | override fun body(): ViewBuilder |
override fun willInit() { setContent {} } |
| UI writing style | Text { attr { text("...") } } |
Text(text = "...", modifier = Modifier...) |
| Source code richness | Minimal (2 kt files) | Rich (5+ kt files, including component encapsulation) |
| Compose scenario notes | — | Need to set KRThreadAdapter.stackSize() = 8MB |
Mode 1: Empty directory scaffolding
When the target directory is empty or does not exist, perform the following steps:
1. Confirm DSL type
Ask the user which DSL to use:
- Kuikly DSL → Use the default command (suitable for new projects, wanting to use Kuikly native APIs)
- Compose DSL → Append to the command
--dsl compose(suitable for developers familiar with Jetpack Compose)
If the user has not explicitly specified, recommend by default Kuikly DSL, because it is more lightweight and has fewer dependencies.
2. Confirm project name and package name
Confirm two parameters before executing the scaffold:
- Project name: corresponds to the
MyApp - Package name / namespace: corresponds to the
--package com.example.myapp
Default suggestions:
- If the user does not provide a project name, the target directory name may be used
- If the user does not provide a package name, it is suggested to use
com.example.<工程名小写>
3. Execute the npm CLI scaffold command
Execute the corresponding command in the parent directory of the target directory to generate the project:
# Kuikly DSL
npx --yes @kuikly-ai/create-kuikly-app@latest --json create-integration MyApp --package com.example.myapp
# Compose DSL
npx --yes @kuikly-ai/create-kuikly-app@latest --json create-integration MyApp --dsl compose --package com.example.myapp
Execution key points:
- Kuikly DSL: do not pass
--dsl, generate the Kuikly DSL project by default - Compose DSL: append
--dsl compose - Target directory: if the user specifies a new directory, keep the project name consistent with the target directory name
- Existing empty directory: prefer to execute the command in its parent directory, then generate a project directory with the same name
4. Generate local.properties
Generate according to the current environment local.properties:
sdk.dir=/path/to/Android/Sdk
5. Verify the project
- Android:
./gradlew :androidApp:assembleDebug, selectandroidApprun on device/emulator - iOS: enter
iosAppdirectory and executepod install --repo-update, open with Xcode.xcworkspacerun - HarmonyOS: use DevEco Studio to open
ohosApprun
6. Follow-up guidance
After generation is complete, inform the user:
- The project has been generated, containing a
routerpage as an example - To add a new page, create a new
shared/src/commonMain/kotlin/under@Pageclass - To integrate into an existing host project, refer to "Mode 2" below
- For environment setup guidance, refer to "Phase 1: Environment Setup" below
Mode 2: Integrating into an Existing Project
When the target directory already contains project files, follow the process below to integrate the Kuikly renderer step by step.
Integration Process
Standard process for integrating Kuikly into an existing project:
- Environment Setup(Phase 1) — Ensure the development environment is ready
- Add KMP shared Module(Phase 2) — Create or add a KMP shared module in the existing project to store cross-platform business code
- Platform Integration(Phase 3/4) — Integrate the renderer and implement adapters in each platform module of the existing project
- Verification(Phase 5) — Write a TestPage to verify successful integration
⚠️ Do not ask the user "whether to create a KMP project" or "whether to overwrite the existing project". When integrating into an existing project, a KMP shared module is required and should be added directly to the existing project, rather than overwriting or replacing the existing project.
Integration Paths by Platform
Select the corresponding integration path based on the project type provided by the user:
| Project Type | Integration Path |
|---|---|
| Android Project | Add KMP shared module → Android platform integration (Phase 3) → Verification |
| iOS Project | Add KMP shared module (requires Mac environment) → iOS platform integration (Phase 4) → Verification |
| HarmonyOS Project | Add KMP shared module → HarmonyOS platform integration (Phase 4 HarmonyOS) → Verification |
| Multi-platform Project | Add KMP shared module → Integrate each platform separately → Verification |
Guide the user through the integration in the order of the sections below.All code examples come from official documentation; do not fabricate APIs from memory.
Phase 1: Environment Setup
Required Tools
| Tool | Purpose | Notes |
|---|---|---|
| Android Studio | Primary IDE for creating KMP projects | For versions ≥ 2024.2.1, switch the Gradle JDK to JDK 17 |
| Kotlin Plugin | KMP support | Android Studio → Settings → Plugins → Marketplace |
| Kotlin Multiplatform Plugin | KMP support | Same as above |
| Kuikly AS Plugin | Scaffolding, one-click project generation | See the official plugin installation documentation for details |
| JDK 17 | Build environment | Configure the JAVA_HOME environment variable |
| Xcode | iOS build (Mac only) | Install if you need to run iOS |
| CocoaPods | iOS dependency management (Mac only) | sudo gem install cocoapods |
Switching the Gradle JDK
When Android Studio version ≥ 2024.2.1, the default Gradle JDK is 21, and it must be manually switched to JDK 17:
Android Studio → Settings → Build, Execution, Deployment → Build Tools → Gradle → Gradle JDK → 选择 JDK 17
Skip iOS Build (Windows / No Mac Environment)
If you do not need to run iOS, comment out the following in shared/build.gradle.kts :
// 注释 plugins 中的:
// kotlin("native.cocoapods")
// 注释 kotlin {} 块中的:
// iosX64()
// iosArm64()
// iosSimulatorArm64()
// cocoapods { ... }
// val iosXxx 相关 sourceSet 配置
// 注释 dependencies 中的:
// add("kspIosArm64", this)
// add("kspIosX64", this)
// add("kspIosSimulatorArm64", this)
Phase 2: Add the KMP shared module
Kuikly's cross-platform business code is stored in the KMP shared module. When integrating into an existing project, you need to add the shared module to the existing project.
Option 1: Create via the Kuikly scaffolding plugin (recommended)
If the existing project can be opened with Android Studio:
- Android Studio → File → New → New Module → Kuikly Module Template
- Fill in the module name (usually
shared), package name, and other information, then click Finish - The scaffolding automatically generates the
sharedmodule, including the@Pagepage,BasePager, and other basic code - In the root
settings.gradle.kts, confirm that it has beeninclude(":shared")
Option 2: Generate the shared baseline via the Node scaffolding
If the scaffolding plugin cannot be used, you can first generate a minimal integration project in a temporary directory, then migrate the shared module into the existing project:
- Run the corresponding command in a temporary directory to generate the project:
- Kuikly DSL:
npx --yes @kuikly-ai/create-kuikly-app@latest --json create-integration TempApp --package com.example.tempapp - Compose DSL:
npx --yes @kuikly-ai/create-kuikly-app@latest --json create-integration TempApp --dsl compose --package com.example.tempapp
- Kuikly DSL:
- Copy the
shared/directory from the generated project to the root directory of the existing project - Add to the root
settings.gradle.ktsininclude(":shared") - Add to the host module
implementation(project(":shared")) - Adjust the
shared/build.gradle.ktsandpackagedeclarations according to the actual project package name, namespace, and version number
In this way, the initial structure of the
sharedmodule is generated directly by the scaffolding, and can be migrated directly into the existing project to continue integration.
Configure the shared module dependency
Configure the Kuikly core dependency in shared/build.gradle.kts :
plugins {
kotlin("multiplatform")
id("com.android.library")
id("com.google.devtools.ksp")
id("com.tencent.kuikly-open.kuikly")
// Compose DSL 额外添加:
// id("org.jetbrains.compose")
// kotlin("plugin.compose")
}
kotlin {
androidTarget { ... }
// 按需配置 iOS / 鸿蒙 target
sourceSets {
val commonMain by getting {
dependencies {
implementation("com.tencent.kuikly-open:core:${kuiklyVersion}")
implementation("com.tencent.kuikly-open:core-annotations:${kuiklyVersion}")
// Compose DSL 额外添加:
// implementation("com.tencent.kuikly-open:compose:${kuiklyVersion}")
}
}
}
}
Depend on shared in the host module
In the existing Android module's build.gradle.kts , add:
dependencies {
implementation(project(":shared"))
}
Check version number consistency
After adding the shared module, check the Kuikly version number in the following files to ensure consistency across platforms:
| File | Description |
|---|---|
shared/build.gradle.kts |
KMP business module |
androidApp/build.gradle.kts |
Android host module |
iosApp/Podfile |
iOS host project (if any) |
ohosApp/entry/oh-package.json5 |
HarmonyOS host project (if any) |
⚠️ After Kuikly 2.5.0, the maven repository needs to be added:
maven("https://mirrors.tencent.com/repository/maven-tencent/")
Verify the shared module
- Android: Compile the
sharedmodule and confirm there are no errors:./gradlew :shared:assembleDebug - iOS: In the
sharedmodule configurationcocoapods, then execute./gradlew :shared:podInstall
Phase 3: Android platform integration
⚠️ All operations below add new files and code only. Do not modify the user's existing launch Activity or any existing code. Kuikly integration is non-intrusive. The user's existing page flow is unaffected. Kuikly pages are entered on demand via
KuiklyRenderActivity.start().
3.1 Add the renderer dependency
In the host module's build.gradle , add:
dependencies {
implementation("com.tencent.kuikly-open:core-render-android:KUIKLY_RENDER_VERSION")
implementation("com.tencent.kuikly-open:core:KUIKLY_CORE_VERSION")
// 其他依赖...
}
⚠️
core-render-androidandcoreversion numbers must be consistent with the KMP project.
3.2 Implement the hosting container
Add KuiklyRenderActivity(do not modify the original Activity):
class KuiklyRenderActivity : AppCompatActivity() {
private lateinit var hrContainerView: ViewGroup
private lateinit var kuiklyRenderViewDelegator: KuiklyRenderViewBaseDelegator
private lateinit var contextCodeHandler: ContextCodeHandler
protected val pageName: String
get() = intent.getStringExtra(KEY_PAGE_NAME) ?: "router"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 1. 创建页面打开封装处理器
contextCodeHandler = ContextCodeHandler(pageName)
// 2. 实例化 Kuikly 委托者
kuiklyRenderViewDelegator = contextCodeHandler.initContextHandler()
setContentView(R.layout.activity_hr)
hrContainerView = findViewById(R.id.hr_container)
// 3. 触发 Kuikly View 实例化
contextCodeHandler.openPage(this, hrContainerView, pageName, createPageData())
}
override fun onResume() {
super.onResume()
kuiklyRenderViewDelegator.onResume()
}
override fun onPause() {
super.onPause()
kuiklyRenderViewDelegator.onPause()
}
override fun onDestroy() {
super.onDestroy()
kuiklyRenderViewDelegator.onDetach()
}
private fun createPageData(): Map<String, Any> = mutableMapOf("appId" to 1)
companion object {
private const val KEY_PAGE_NAME = "pageName"
private const val KEY_PAGE_DATA = "pageData"
fun start(context: Context, pageName: String, pageData: JSONObject) {
val intent = Intent(context, KuiklyRenderActivity::class.java)
intent.putExtra(KEY_PAGE_NAME, pageName)
intent.putExtra(KEY_PAGE_DATA, pageData.toString())
context.startActivity(intent)
}
}
}
The corresponding layout file activity_hr.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/hr_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<View
android:id="@+id/hr_loading"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<View
android:id="@+id/hr_error"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
3.3 Implement the adapter (required)
Kuikly uses the adapter pattern to delegate capabilities such as image loading, logging, routing, and threading to the host implementation.
Image loading adapter (required)
object KRImageAdapter : IKRImageAdapter {
override fun fetchDrawable(
imageLoadOption: HRImageLoadOption,
callback: (drawable: Drawable?) -> Unit
) {
// 使用宿主图片库(如 Glide、Coil)加载图片
// ⚠️ 此方法可能在非 UI 线程调用,注意线程安全
}
}
Logging adapter (required)
object KRLogAdapter : IKRLogAdapter {
override val asyncLogEnable: Boolean get() = false
override fun i(tag: String, msg: String) { Log.i(tag, msg) }
override fun d(tag: String, msg: String) { Log.d(tag, msg) }
override fun e(tag: String, msg: String) { Log.e(tag, msg) }
}
Page routing adapter (required)
object KRRouterAdapter : IKRRouterAdapter {
override fun openPage(context: Context, pageName: String, pageData: JSONObject) {
KuiklyRenderActivity.start(context, pageName, pageData)
}
override fun closePage(context: Context) {
(context as? Activity)?.finish()
}
}
Thread adapter (required)
class KRThreadAdapter : IKRThreadAdapter {
override fun executeOnSubThread(task: () -> Unit) {
subThreadPoolExecutor.execute(task)
}
/**
* Compose 场景下建议设置 8MB 以避免 StackOverflowException
*/
override fun stackSize(): Long = 8 * 1024 * 1024
}
private val subThreadPoolExecutor by lazy {
Executors.newFixedThreadPool(2)
}
Exception adapter (recommended)
object KRExceptionAdapter : IKRUncaughtExceptionHandlerAdapter {
override fun uncaughtException(throwable: Throwable) {
if (BuildConfig.DEBUG) {
throw throwable
} else {
Log.e("KRError", throwable.stackTraceToString())
}
}
}
3.4 Register adapters
In KuiklyRenderActivity of companion object , initialize:
companion object {
init {
initKuiklyAdapter()
}
private fun initKuiklyAdapter() {
with(KuiklyRenderAdapterManager) {
krImageAdapter = KRImageAdapter
krLogAdapter = KRLogAdapter
krUncaughtExceptionHandlerAdapter = KRExceptionAdapter
krRouterAdapter = KRRouterAdapter
krThreadAdapter = KRThreadAdapter()
// 按需实现其他适配器
// krFontAdapter = KRFontAdapter
// krColorParseAdapter = KRColorParserAdapter(application)
}
}
}
3.5 Adapters implemented as needed
Color value conversion adapter
object KRColorAdapter : IKRColorParserAdapter {
override fun toColor(colorStr: String): Int? {
// 自定义颜色转换逻辑(如支持语义化颜色名)
return null
}
}
Custom font adapter
object KRFontAdapter : IKRFontAdapter {
override fun getTypeface(fontFamily: String, result: (Typeface?) -> Unit) {
val typeface = when (fontFamily) {
"Satisfy-Regular" -> Typeface.createFromAsset(application.assets, "fonts/$fontFamily.ttf")
else -> null
}
result(typeface)
}
// 固定 density,使布局不受系统"显示大小"设置影响
override fun getDisplayMetrics(useHostDisplayMetrics: Boolean?): DisplayMetrics {
return DisplayMetrics().apply {
density = 2f
scaledDensity = 2f
}
}
}
Phase 4: iOS platform integration
4.1 Add renderer dependency
Option 1: CocoaPods (recommended)
In Podfile , add:
source 'https://cdn.cocoapods.org/'
platform :ios, '14.1'
target 'KuiklyTest' do
inhibit_all_warnings!
pod 'OpenKuiklyIOSRender', 'KUIKLY_RENDER_VERSION'
# 链接业务代码(本地路径)
pod 'shared', :path => '/path/to/your/KMP/shared'
end
Run pod install --repo-update to install dependencies.
Option 2: SPM (Swift Package Manager)
- Xcode → Project → Package Dependencies → click +
- Enter the repository address:
https://github.com/Tencent-TDS/KuiklyUI.git - Select the same version as the KMP project and click Add Package
Business .xcframework is recommended to be encapsulated as a local Swift Package:
// Package.swift
.binaryTarget(
name: "shared",
path: "./shared.xcframework"
)
4.2 Implement the hosting container
Option 1: UIViewController approach (recommended)
// KuiklyRenderViewController.h
@interface KuiklyRenderViewController : UIViewController
- (instancetype)initWithPageName:(NSString *)pageName pageData:(NSDictionary *)pageData;
@end
// KuiklyRenderViewController.m
#import <OpenKuiklyIOSRender/KuiklyRenderViewControllerBaseDelegator.h>
@interface KuiklyRenderViewController()<KuiklyRenderViewControllerBaseDelegatorDelegate>
@property (nonatomic, strong) KuiklyRenderViewControllerBaseDelegator *delegator;
@end
@implementation KuiklyRenderViewController
- (instancetype)initWithPageName:(NSString *)pageName pageData:(NSDictionary *)pageData {
if (self = [super init]) {
// ⚠️ 必须使用 KuiklyRenderViewControllerDelegator,不要使用 BaseDelegator
_delegator = [[KuiklyRenderViewControllerDelegator alloc] initWithPageName:pageName pageData:pageData];
_delegator.delegate = self;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[_delegator viewDidLoadWithView:self.view];
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
[_delegator viewDidLayoutSubviews];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[_delegator viewWillAppear];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[_delegator viewDidAppear];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[_delegator viewWillDisappear];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[_delegator viewDidDisappear];
}
#pragma mark - KuiklyRenderViewControllerBaseDelegatorDelegate
- (UIView *)createLoadingView {
UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor whiteColor];
return v;
}
- (UIView *)createErrorView {
UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor whiteColor];
return v;
}
// 返回业务代码编译成的 framework 名字
- (void)fetchContextCodeWithPageName:(NSString *)pageName resultCallback:(KuiklyContextCodeCallback)callback {
if (callback) {
callback(@"shared", nil);
}
}
@end
⚠️ Must use
KuiklyRenderViewControllerDelegator, do not useKuiklyRenderViewControllerBaseDelegator, otherwise it will cause functional abnormalities.
4.3 Implement adapters (must be implemented)
Image loading adapter (required)
// KuiklyRenderComponentExpandHandler.m
#import <SDWebImage/UIImageView+WebCache.h>
@implementation KuiklyRenderComponentExpandHandler
+ (void)load {
[KuiklyRenderBridge registerComponentExpandHandler:[self new]];
}
// ✅ 推荐方法(带 src 一致性验证)
- (BOOL)hr_setImageWithUrl:(NSString *)loadURL
imageParams:(NSDictionary *)imageParams
complete:(ImageCompletionBlock)completeBlock {
// ⚠️ SDWebImage 需设置 SDWebImageAvoidAutoSetImage,避免图片错乱
[[SDWebImageManager sharedManager]
loadImageWithURL:[NSURL URLWithString:loadURL]
options:SDWebImageAvoidAutoSetImage
progress:nil
completed:^(UIImage *image, NSData *data, NSError *error,
SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (completeBlock) {
// ⚠️ 传入的 imageURL 必须是原始参数 loadURL,不是 SDWebImage 回调的 imageURL
completeBlock(image, error, [NSURL URLWithString:loadURL]);
}
}];
return YES;
}
@end
Page routing adapter (required)
// KRRouterHandler.m
@implementation KRRouterHandler
+ (void)load {
[KRRouterModule registerRouterHandler:[self new]];
}
- (void)openPageWithName:(NSString *)pageName
pageData:(NSDictionary *)pageData
controller:(UIViewController *)controller {
KuiklyRenderViewController *vc = [[KuiklyRenderViewController alloc]
initWithPageName:pageName pageData:pageData];
[controller.navigationController pushViewController:vc animated:YES];
}
- (void)closePage:(UIViewController *)controller {
[controller.navigationController popViewControllerAnimated:YES];
}
@end
Log adapter (recommended)
@implementation KuiklyLogHandler
- (BOOL)asyncLogEnable { return NO; }
- (void)logInfo:(NSString *)message { NSLog(@"%@", message); }
- (void)logDebug:(NSString *)message {
#if DEBUG
NSLog(@"%@", message);
#endif
}
- (void)logError:(NSString *)message { NSLog(@"%@", message); }
@end
Exception adapter (recommended)
Override the exception method of KuiklyRenderViewControllerBaseDelegatorDelegate :
- (void)onUnhandledException:(NSString *)exReason
stack:(NSString *)callstackStr
mode:(KuiklyContextMode)mode {
// 处理异常或上报
}
4.4 Adapters implemented as needed
APNG image loading adapter
@implementation KRAPNGViewHandler
+ (void)load {
[KRAPNGView registerAPNGViewCreator:^id<APNGImageViewProtocol>(CGRect frame) {
return [[KRAPNGViewHandler alloc] initWithFrame:frame];
}];
}
@end
Phase 4 (HarmonyOS): HarmonyOS platform integration
⚠️ Before this, please ensure that the Kuikly integration on the KMP side has been completed (Phase 2). The HarmonyOS emulator does not support X86-based Macs; it is recommended to use an Apple Silicon (Arm) Mac for HarmonyOS development.
5.1 Add renderer dependency
Edit the oh-package.json5of the entry module, and add the Kuikly renderer dependency:
// entry/oh-package.json5
{
...
"dependencies": {
...
"@kuikly-open/render": "KUIKLY_RENDER_VERSION"
}
}
⚠️
KUIKLY_RENDER_VERSIONneeds to be replaced with the actual version number, and must be consistent with the KMP project.
Click Sync Nowin the upper right corner (or execute in the entry directory ohpm install)。
5.2 Create the HarmonyOS runtime initialization interface
The Kuikly HarmonyOS rendering is implemented based on the ArkUI C-API, and the runtime initialization interface needs to be exposed to the ArkTS layer through NAPI.
Add C++ (NAPI) support
Add C++ (NAPI) support to the entry module of the HarmonyOS project: right-click the entry directory → New → Native C++。
Add the NAPI initialization entry function
In entry/src/main/cpp/napi_init.cpp , add the InitKuikly initialization entry:
// entry/src/main/cpp/napi_init.cpp
#include "napi/native_api.h"
static napi_value InitKuikly(napi_env env, napi_callback_info info) {
// 添加业务代码初始化逻辑,具体见后续「链接 Kuikly 业务代码」步骤
return nullptr;
}
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
napi_property_descriptor desc[] = {
{"initKuikly", nullptr, InitKuikly, nullptr, nullptr, nullptr, napi_default, nullptr},
};
napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
return exports;
}
EXTERN_C_END
static napi_module demoModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "entry",
.nm_priv = ((void*)0),
.reserved = { 0 },
};
extern "C" __attribute__((constructor)) void RegisterEntryModule(void) {
napi_module_register(&demoModule);
}
In entry/src/main/cpp/types/libentry/index.d.ts , declare the interface:
// entry/src/main/cpp/types/libentry/index.d.ts
export const initKuikly: () => number;
Associate NativeManager
Under entry/src/main/ets/kuikly/ , create MyNativeManager.ets:
// entry/src/main/ets/kuikly/MyNativeManager.ets
import { KuiklyNativeManager } from '@kuikly-open/render';
import Napi from 'libentry.so';
class MyNativeManager extends KuiklyNativeManager {
protected loadNative(): number {
return Napi.initKuikly();
}
}
const globalNativeManager = new MyNativeManager();
export default globalNativeManager;
5.3 Implement the hosting container
Create the delegate class
Under entry/src/main/ets/kuikly/ , create KuiklyViewDelegate.etsto register custom Modules:
// entry/src/main/ets/kuikly/KuiklyViewDelegate.ets
import { IKuiklyViewDelegate, KRRenderModuleExportCreator } from '@kuikly-open/render';
import { KRBridgeModule } from './modules/KRBridgeModule';
export class KuiklyViewDelegate extends IKuiklyViewDelegate {
// 注册自定义 Module
getCustomRenderModuleCreatorRegisterMap(): Map<string, KRRenderModuleExportCreator> {
const map: Map<string, KRRenderModuleExportCreator> = new Map();
map.set(KRBridgeModule.MODULE_NAME, () => new KRBridgeModule());
return map;
}
}
Implement the Kuikly hosting page
In entry/src/main/ets/pages/Index.ets , use the Kuikly component:
// entry/src/main/ets/pages/Index.ets
import { KRRecord, Kuikly } from '@kuikly-open/render';
import router from '@ohos.router';
import { KuiklyViewDelegate } from '../kuikly/KuiklyViewDelegate';
import globalNativeManager from '../kuikly/MyNativeManager';
@Entry
@Component
struct Index {
private kuiklyViewDelegate = new KuiklyViewDelegate();
private pageName: string | null = null;
private pageData?: KRRecord;
aboutToAppear(): void {
const params = router.getParams() as Record<string, Object>;
this.pageName = params?.pageName as string;
this.pageData = (params?.pageData as KRRecord | null) ?? {};
}
build() {
Stack() {
Kuikly({
pageName: this.pageName ?? 'router',
pageData: this.pageData ?? {},
delegate: this.kuiklyViewDelegate,
nativeManager: globalNativeManager,
})
}
.width('100%').height('100%')
.expandSafeArea([SafeAreaType.KEYBOARD])
}
// 生命周期转发
onPageShow(): void { this.kuiklyViewDelegate.pageDidAppear(); }
onPageHide(): void { this.kuiklyViewDelegate.pageDidDisappear(); }
}
Kuikly component parameter description:
| Parameter | Description |
|---|---|
pageName |
Page name, corresponding to the name defined in the @Page annotation |
pageData |
Page data, the parameters passed to the Kuikly page |
delegate |
Delegate implementation, used to register custom Modules |
nativeManager |
Native manager instance |
initialSize |
(Optional) initial size { width, height }, to create the cross-platform page in advance |
onControllerReadyCallback |
(Optional) controller ready callback |
5.4 Implementing adapters (required)
Log adapter (recommended)
// entry/src/main/ets/kuikly/adapter/LogAdapter.ets
import { IKRLogAdapter } from '@kuikly-open/render';
import hilog from '@ohos.hilog';
export class LogAdapter implements IKRLogAdapter {
i(tag: string, msg: string): void {
hilog.info(0x30, tag, '%{public}s', msg);
}
d(tag: string, msg: string): void {
hilog.debug(0x30, tag, '%{public}s', msg);
}
e(tag: string, msg: string): void {
hilog.error(0x30, tag, '%{public}s', msg);
}
}
Page routing adapter (required)
// entry/src/main/ets/kuikly/adapter/RouterAdapter.ets
import { IKRRouterAdapter, KRRecord } from '@kuikly-open/render';
import router from '@ohos.router';
import { common } from '@kit.AbilityKit';
export class RouterAdapter implements IKRRouterAdapter {
openPage(context: common.UIAbilityContext, pageName: string, pageData: KRRecord): void {
router.pushUrl({
url: 'pages/Index',
params: { pageName, pageData }
});
}
closePage(context: common.UIAbilityContext): void {
router.back();
}
}
Initializing adapters
In EntryAbility.ets 's onWindowStageCreate , register the adapters:
// entry/src/main/ets/entryability/EntryAbility.ets
import { KuiklyRenderAdapterManager } from '@kuikly-open/render';
import { LogAdapter } from '../kuikly/adapter/LogAdapter';
import { RouterAdapter } from '../kuikly/adapter/RouterAdapter';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage): void {
windowStage.getMainWindowSync().setWindowLayoutFullScreen(true);
// 注册适配器
KuiklyRenderAdapterManager.krLogAdapter = new LogAdapter();
KuiklyRenderAdapterManager.krRouterAdapter = new RouterAdapter();
windowStage.loadContent('pages/Index', (err, data) => { ... });
}
}
In multi-ability scenarios, initialization can be moved earlier to
AbilityStageto avoid overwriting each other.
5.5 Implementing a business Module (optional)
Inherit KuiklyRenderBaseModuleand implement native capabilities for the Kotlin side to call:
// entry/src/main/ets/kuikly/modules/KRBridgeModule.ets
import { KuiklyRenderBaseModule, KRRenderModuleMethodCallback } from '@kuikly-open/render';
import router from '@ohos.router';
export class KRBridgeModule extends KuiklyRenderBaseModule {
static readonly MODULE_NAME = 'HRBridgeModule';
toast(params: string, callback: KRRenderModuleMethodCallback): void {
// 展示 Toast
}
closePage(params: string, callback: KRRenderModuleMethodCallback): void {
router.back();
}
}
5.6 Linking Kuikly business code
Kuikly business code is compiled for the HarmonyOS platform into .so artifacts, which need to be linked into the HarmonyOS project.
Generate so artifacts and header files
Execute in the KMP project:
./gradlew -c settings.ohos.gradle.kts :shared:linkOhosArm64
Copy business artifacts
Copy the generated libshared.so and header file libshared_api.h into the C++ module directory.
Modify CMakeLists.txt
set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
# Kuikly SDK
add_library(kuikly_render ALIAS render::kuikly)
# 业务产物
add_library(kuikly_shared SHARED IMPORTED)
set_target_properties(kuikly_shared
PROPERTIES
IMPORTED_LOCATION ${NATIVERENDER_ROOT_PATH}/../../../libs/${OHOS_ARCH}/libshared.so)
# 链接到入口模块
target_link_libraries(entry PUBLIC libace_napi.z.so kuikly_shared kuikly_render)
Implement the InitKuikly function
// entry/src/main/cpp/napi_init.cpp
#include "libshared_api.h"
#include "napi/native_api.h"
static napi_value InitKuikly(napi_env env, napi_callback_info info) {
auto api = libshared_symbols();
int handler = api->kotlin.root.initKuikly();
napi_value result;
napi_create_int32(env, handler, &result);
return result;
}
Copy resource files (if any)
Copy the resources under shared/src/commonMain/assets/ to entry/src/main/resources/resfile/。
5.7 Adapters to implement as needed
Image loading adapter (C++ layer)
Register via KRRegisterImageAdapterV2 or KRRegisterImageAdapterV3 :
// entry/src/main/cpp/napi_init.cpp
#include <Kuikly/Kuikly.h>
// V3 实现(支持 imageParams)
static int32_t MyImageAdapterV3(const void *context, const char *src,
KRAnyData *imageParams, KRSetImageCallback callback) {
// 自定义图片加载逻辑
return 0; // 返回 1 表示已处理
}
static napi_value InitKuikly(napi_env env, napi_callback_info info) {
KRRegisterImageAdapterV3(MyImageAdapterV3);
// ...
}
V3 takes precedence over V2.
imageParamsis the JSONObject passed from the cross-platform side, which can be iterated viaKRAnyDataVisitMap.
Custom font adapter (C++ layer)
Register via KRRegisterFontAdapter :
static char *MyFontAdapter(const char *fontFamily, char **fontBuffer,
size_t *len, KRFontDataDeallocator *deallocator) {
if (isEqual(fontFamily, "Satisfy-Regular")) {
return "rawfile:Satisfy-Regular.ttf";
}
return (char *)customFontPath.c_str();
}
static napi_value InitKuikly(napi_env env, napi_callback_info info) {
KRRegisterFontAdapter(MyFontAdapter, "Satisfy-Regular");
// ...
}
Color value conversion adapter (C++ layer)
Register via KRRegisterColorAdapter :
static int64_t MyColorAdapter(const char* str) {
// 自定义颜色解析,返回 -1 则由 Kuikly 自动转换
return -1;
}
static napi_value InitKuikly(napi_env env, napi_callback_info info) {
KRRegisterColorAdapter(MyColorAdapter);
// ...
}
Phase 5: Write a TestPage to verify the integration
In the shared module of the KMP project, create a new TestPage:
@Page("test")
class TestPage : Pager() {
override fun body(): ViewBuilder {
return {
attr {
allCenter()
backgroundColor(Color.WHITE)
}
Text {
attr {
fontSize(20f)
color(Color.GREEN)
text("Hello Kuikly")
}
}
}
}
}
Android verification
In the user'sexisting page(such as on a button's click event), navigate to the Kuikly page in the following way for verification,do not modify the launch Activity:
// 在原有页面的任意位置(如按钮点击事件中)调用
KuiklyRenderActivity.start(context, "test", JSONObject())
iOS verification
KuiklyRenderViewController *vc = [[KuiklyRenderViewController alloc]
initWithPageName:@"test" pageData:nil];
[self.navigationController pushViewController:vc animated:YES];
If the green "Hello Kuikly" text appears, the integration is successful.
Integrating business code into an existing project
Android
- Execute in the KMP project:
./gradlew :shared:bundleDebugAar - The artifacts are located at
shared/build/output/aar/ - Integrate the AAR into the host project as a local or remote dependency
iOS
- Execute Kotlin/Native compilation in the KMP project to generate
shared.xcframework - Integrate into the host project via a local Pod or SPM
Integration checklist
Android
- [ ] 添加 core-render-android 和 core 依赖(版本与 KMP 一致)
- [ ] 实现 KuiklyRenderActivity
- [ ] 实现图片加载适配器(IKRImageAdapter)
- [ ] 实现日志适配器(IKRLogAdapter)
- [ ] 实现页面路由适配器(IKRRouterAdapter)
- [ ] 实现线程适配器(IKRThreadAdapter)
- [ ] 在 companion object init 中注册所有适配器
- [ ] 编写 TestPage 验证接入成功
iOS
- [ ] Podfile 添加 OpenKuiklyIOSRender 依赖(版本与 KMP 一致)
- [ ] 执行 pod install --repo-update
- [ ] 实现 KuiklyRenderViewController(使用 KuiklyRenderViewControllerDelegator)
- [ ] 实现图片加载适配器(hr_setImageWithUrl:imageParams:complete:)
- [ ] 实现页面路由适配器(KRRouterHandler)
- [ ] fetchContextCodeWithPageName: 返回正确的 framework 名字("shared")
- [ ] 链接业务代码 .xcframework 或 Pod
- [ ] 编写 TestPage 验证接入成功
HarmonyOS
- [ ] oh-package.json5 添加 @kuikly-open/render 依赖(版本与 KMP 一致)
- [ ] 添加 C++(NAPI)支持,实现 napi_init.cpp 中的 InitKuikly 入口
- [ ] 创建 MyNativeManager.ets 关联 KuiklyNativeManager
- [ ] 创建 KuiklyViewDelegate.ets 注册自定义 Module
- [ ] 实现 Kuikly 承载页面(pages/Index.ets)
- [ ] 实现日志适配器(IKRLogAdapter)
- [ ] 实现页面路由适配器(IKRRouterAdapter)
- [ ] 在 EntryAbility.onWindowStageCreate 中注册适配器
- [ ] 编译 so 产物并链接到鸿蒙工程(CMakeLists.txt)
- [ ] 拷贝资源文件到 entry/src/main/resources/resfile/
- [ ] 编写 TestPage 验证接入成功
Kuikly resources and support
Official resources
| Resource | Link |
|---|---|
| Official documentation | https://kuikly.tds.qq.com/DevGuide/dev-guide-overview.html |
| GitHub repository | https://github.com/Tencent-TDS/KuiklyUI |
| Version changelog | https://kuikly.tds.qq.com/ChangeLog/changelog.html |
Welcome to Star the Kuikly open-source project on GitHub! If you encounter any problems while using it, you are also welcome to submit an Issue.
Local documentation index
- Environment setup →
docs/QuickStart/env-setup.md - KMP project integration →
docs/QuickStart/common.md - Android integration →
docs/QuickStart/android.md - iOS integration →
docs/QuickStart/iOS.md - HarmonyOS integration →
docs/QuickStart/harmony.md - H5 integration →
docs/QuickStart/h5.md - Mini program integration →
docs/QuickStart/Miniapp.md - First page →
docs/QuickStart/hello-world.md - Extend native View →
skills/expanding-native-view/SKILL.md - Extend native API →
skills/expanding-native-api/SKILL.md
Contact assistant
In the following situations, we recommend contacting the Kuikly assistant for help:
- Dynamic release — Questions about dynamic capabilities, remote dynamic release processes, version canary strategies, etc.
- Troubleshooting complex issues — Difficult problems encountered during integration, scenarios not covered by this documentation
- Advanced capability consultation — In-depth topics such as performance tuning, custom rendering pipelines, cross-platform communication, etc.
- Business integration support — Large-scale business integration requires official support
📬 Please contact us through the assistant contact information provided in the official documentation or on the GitHub repository page.