Using Kotlin from local Swift packages
In this tutorial, you'll learn how to add a dependency on a Kotlin framework in a local package in the Swift package manager. This is useful if you want to simultaneously connect your Kotlin Multiplatform module to several SPM modules in your Xcode project.
Set up the project
The feature is available starting with Kotlin 2.0.0.
If you still haven't upgraded to Kotlin 2.0.0, you can use a special Kotlin version, 1.9.24-spm2
from the https://packages.jetbrains.team/maven/p/mpp/dev
Maven repository. You can add the repository, for instance, in your settings.gradle.kts
:
The tutorial assumes that your project is using direct integration approach with the embedAndSignAppleFrameworkForXcode
task in the project's build phase. If you're connecting a Kotlin framework through CocoaPods plugin or through Swift package with binaryTarget
, migrate first.
Migrate from SPM binaryTarget integration to local direct integration
To migrate from the SPM integration with binaryTarget
:
In Xcode, clean build directories using Product | Clean Build Folder or with the Cmd + Shift + K shortcut.
In every
Package.swift
file, remove both dependencies to the package with a Kotlin framework inside and target dependencies to the products.To set up direct integration, follow the steps described in this tutorial.
Migrate from CocoaPods plugin to direct integration
To migrate from the CocoaPods plugin:
In Xcode, clean build directories using Product | Clean Build Folder or with the Cmd + Shift + K shortcut.
In the directory with
Podfile
, run the following command:pod deintegrateRemove the
cocoapods {}
block from yourbuild.gradle(.kts)
files.Delete the
.podspec
andPodfile
files.To set up direct integration, follow the steps described in this tutorial.
Connect the framework to your project
To connect the Kotlin framework to your Xcode project and use the Kotlin code in a local Swift package:
In Xcode, go to Product | Scheme | Edit scheme or click the schemes icon in the top bar and select Edit scheme:
Select the Build | Pre-actions item, then click + | New Run Script Action:
Add the following script and replace
:shared
with your Gradle project name:cd "$SRCROOT/.." ./gradlew :shared:embedAndSignAppleFrameworkForXcodeChoose your app's target in the Provide build settings from section:
Use the code from Kotlin in the local Swift package added to your Xcode project:
Build the project in Xcode. If everything is set up correctly, the project build will be successful.