我无法让 Ktor 在 KMM 项目中工作,我只是Unresolved reference: HttpClient
在尝试引用任何 Ktor 类时遇到错误。如果我尝试手动添加 ktor 导入,它会说Unresolved reference io
. 其他依赖项,如Kermit
解决问题,似乎只是 Ktor 的问题。这是我重现的简单步骤:
在 Android Studio 中(我已经尝试过 4.1.3 和 4.2 Beta 6),我去 File -> New -> KMM Application。
在共享模块 build.gradle.kts 中,我添加了 ktor 客户端的依赖项:
val commonMain by getting {
dependencies {
implementation("io.ktor:ktor-client-core:1.5.2")
}
}
- 在
Greeting
commonMain 类中,我尝试创建一个 HttpClient ,就像 Ktor 文档https://kotlinlang.org/docs/mobile/use-ktor-for-networking.html#select-an-engine中所说的那样:
class Greeting {
val httpClient: HttpClient = HttpClient()
fun greeting(): String {
return "Hello, ${Platform().platform}!"
}
}
我得到Unresolved reference: HttpClient
. ktor 导入不起作用。
我尝试过的事情:
- 还添加了 Android 和 iOS 客户端依赖项。
- 按照此处的建议将 enableFeaturePreview("GRADLE_METADATA") 添加到 settings.gradle.kts: How to fix 'Unresolved reference: HttpClient' with ktor-client-core target linuxX64
- 清理、与 gradle 同步、使现金无效并重新启动、关闭 AS 并重新打开、构建项目。
我真的不知道为什么这不起作用,这似乎是最简单的设置。这是我的 build.gradle 文件和设置文件(从新的 KMM 项目向导自动生成)
共享模块 build.gradle.kts
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
plugins {
kotlin("multiplatform")
id("com.android.library")
}
kotlin {
android()
ios {
binaries {
framework {
baseName = "shared"
}
}
}
sourceSets {
val commonMain by getting {
dependencies {
implementation("io.ktor:ktor-client-core:1.5.2")
}
}
val commonTest by getting {
dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
}
}
val androidMain by getting {
dependencies {
implementation("com.google.android.material:material:1.2.1")
}
}
val androidTest by getting {
dependencies {
implementation(kotlin("test-junit"))
implementation("junit:junit:4.13")
}
}
val iosMain by getting
val iosTest by getting
}
}
android {
compileSdkVersion(29)
sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
defaultConfig {
minSdkVersion(24)
targetSdkVersion(29)
}
}
val packForXcode by tasks.creating(Sync::class) {
group = "build"
val mode = System.getenv("CONFIGURATION") ?: "DEBUG"
val sdkName = System.getenv("SDK_NAME") ?: "iphonesimulator"
val targetName = "ios" + if (sdkName.startsWith("iphoneos")) "Arm64" else "X64"
val framework = kotlin.targets.getByName<KotlinNativeTarget>(targetName).binaries.getFramework(mode)
inputs.property("mode", mode)
dependsOn(framework.linkTask)
val targetDir = File(buildDir, "xcode-frameworks")
from({ framework.outputDirectory })
into(targetDir)
}
tasks.getByName("build").dependsOn(packForXcode)
项目build.gradle.kts
buildscript {
repositories {
gradlePluginPortal()
jcenter()
google()
mavenCentral()
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.10")
classpath("com.android.tools.build:gradle:4.0.1")
}
}
allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}
settings.gradle.kts
pluginManagement {
repositories {
google()
jcenter()
gradlePluginPortal()
mavenCentral()
}
}
rootProject.name = "core"
include(":androidApp")
include(":shared")