KMM项目iOS端无法识别shared模块类 添加Ktor依赖后出现报错
问题根因
你在commonMain源集中添加了仅支持JVM平台的依赖,导致shared模块的iOS侧编译失败,Xcode自然无法识别shared模块导出的类,出现Cannot find "Greeting" in scope报错。安卓侧因为本身是JVM环境所以不受影响可以正常运行。
修复步骤
- 修正依赖配置
commonMain源集只能放置全平台兼容的依赖,平台专属依赖要放到对应平台的源集下,正确的Ktor多平台依赖配置参考如下:
val commonMain by getting { dependencies { // 全平台兼容的Ktor核心依赖 implementation("io.ktor:ktor-client-core:$ktorVersion") implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion") implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion") } } val androidMain by getting { dependencies { // Android/JVM专属的Ktor客户端引擎 implementation("io.ktor:ktor-client-okhttp:$ktorVersion") } } val iosMain by getting { dependencies { // iOS专属的Ktor客户端引擎 implementation("io.ktor:ktor-client-darwin:$ktorVersion") } }
- 解决多平台实验特性报错
在项目根目录的gradle.properties文件中添加如下配置,即可消除提示:
kotlin.mpp.experimental=true
- 清理构建缓存
修改完配置后,在Android Studio中依次点击File > Invalidate Caches,勾选清理文件系统缓存选项后重启IDE,再重新构建shared模块,之后iOS应用即可正常识别shared模块中的类。
内容的提问来源于stack exchange,提问作者Opr Vld
相关产品推荐
相关产品推荐

