Kotlin Multiplatform Development stable Help

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-spm from the https://packages.jetbrains.team/maven/p/mpp/dev Maven repository. You can add the repository, for instance, in your settings.gradle.kts:

pluginManagement { repositories { maven("https://packages.jetbrains.team/maven/p/mpp/dev") //... } } dependencyResolutionManagement { repositories { maven("https://packages.jetbrains.team/maven/p/mpp/dev") //... } }

The tutorial assumes that your project is using direct integration approach with the embedAndSignAppleFrameworkForXcode task. If you're connecting a Kotlin framework through CocoaPods plugin, migrate first.

Migrate from CocoaPods plugin to direct integration

To migrate from the CocoaPods plugin:

  1. In the directory with Podfile, run the following command:

    pod deintegrate
  2. Remove the cocoapods {} block from your build.gradle(.kts) files.

  3. Delete the .podspec and Podfile files.

  4. 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:

  1. In Xcode, go to Product | Scheme | Edit scheme or click the schemes icon in the top bar and select Edit scheme:

    Edit scheme
  2. Select the Build | Pre-actions item, then click + | New Run Script Action:

    New run script action
  3. Add the following script and replace :shared with your Gradle project name:

    cd "$SRCROOT/.." ./gradlew :shared:embedAndSignAppleFrameworkForXcode
  4. Choose your app's target in the Provide build settings from section:

    Filled run script action
  5. Use the code from Kotlin in the local Swift package added to your Xcode project:

    SPM usage
  6. Build the project in Xcode. If everything is set up correctly, the project build will be successful.

What's next

Last modified: 10 June 2024