Created by Paris Tsiogas, Head of Mobile Development @ Desquared March 25, 2021

What is KMM?

Kotlin Multiplatform Mobile (KMM) is an SDK that allows you to use the same business logic code in both iOS and Android applications with the power of Kotlin language. The Kotlin/Native compiler produces a framework that can be used in your iOS project.

The problem

KMM can be also applied to existing projects and increase code sharing between Android & iOS.

The main question is how the KMM code is shared with the iOS project and what is the repository strategy you could follow in order to do so and do not distract too much the way your team works. This article will try to give a solution to the above.

Solution overview

Because we are focusing on existing apps, we will assume that you already work with 2 repositories (Android & iOS). We will also assume that you have already integrated KMM at your Android repository. After that we will demonstrate a way to compile your KMM code as a Swift Package and publish it at the Android repository. To help you understand every step, we have created a KotlinMultiplatformSwiftPackageExample and performed every step in a separate commit.

Diagram 1: Repository strategy and Swift package sharing

Diagram 1: Repository strategy and Swift package sharing

Swift Package Manager

Let's quote some basic info about SPM from the official documents.

The Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies. The Package Manager is included in Swift 3.0 and above.

Swift packages are reusable components of Swift, Objective-C, Objective-C++, C, or C++ code that developers can use in their projects. They bundle source files, binaries, and resources in a way that’s easy to use in your app’s project. Xcode supports creating and publishing Swift packages, as well as adding, removing, and managing package dependencies. Its support for Swift packages is built on top of the open source Swift Package Manager project.

Every package lives in a repository and it'a accessible from Xcode through its URL.

We will make use of the Multiplatform Swift Package gradle plugin in order to generate a XCFramework and create a matching Package.swift file to distribute it as a binary target.

Step 1: Install Multiplatform Swift Package plugin (946c545)

Spot the build.gradle.kts inside your shared module. Add the following lines in order to install the plugin. After that perform a gradle sync.

plugins {
    id("com.chromaticnoise.multiplatform-swiftpackage") version "2.0.3"

Step 2: Setup the plugin (1d65c14)