Mit Kotlin Multiplatform (KMP) teilst du Business-Logik zwischen iOS und Android, während UI und APIs plattformspezifisch bleiben. Deep Link Handling passt gut zu diesem Modell: URL-Parsing und Route-Matching sind reine Logik (geteilt), das Empfangen von URLs und die Navigation sind plattformspezifisch. In diesem Artikel baust du Schritt für Schritt einen geteilten Deep Link Router in KMP.
Android-spezifische Deep-Link-Patterns findest du unter Deep Link Handling in Kotlin: moderne Android-Patterns. Einen plattformübergreifenden Überblick gibt der Leitfaden zu Cross-Platform Deep Linking für 2026.
Architektur
KMP-Projekte nutzen expect/actual -Deklarationen für plattformspezifischen Code. Für Deep Linking heißt das:
- Shared Module (
commonMain): URL-Parsing, Route-Matching, Parameter auslesen - Android (
androidMain): Intents verarbeiten, Navigation zwischen Activities - iOS (
iosMain): Universal Links verarbeiten, Navigation mit UIKit/SwiftUI
commonMain/
DeepLinkRouter.kt // Logik für Route-Matching
DeepLinkAction.kt // Action-Typen
UrlParser.kt // Hilfsfunktionen zum URL-Parsing
androidMain/
AndroidDeepLinkHandler.kt // Intent → Action
AndroidNavigator.kt // Navigation mit Activity/Fragment
iosMain/
IosDeepLinkHandler.kt // NSUserActivity → Action
IosNavigator.kt // Navigation mit UIKit
Shared Module: Route Matching
Routen definieren
// commonMain/DeepLinkRouter.kt
data class RouteMatch(
val screen: String,
val params: Map<String, String>
)
data class RoutePattern(
val regex: Regex,
val screen: String,
val paramNames: List<String>
)
object DeepLinkRouter {
private val routes: List<RoutePattern> = listOf(
routePattern("/products/{productId}", "ProductDetail"),
routePattern("/offers/{offerId}", "OfferDetail"),
routePattern("/referral/{referrerId}", "Referral"),
routePattern("/categories/{categoryId}/products", "CategoryProducts"),
routePattern("/search", "Search")
)
fun match(urlString: String): RouteMatch? {
val parsed = parseUrl(urlString) ?: return null
val path = parsed.path
for (route in routes) {
val matchResult = route.regex.matchEntire(path) ?: continue
val params = mutableMapOf<String, String>()
route.paramNames.forEachIndexed { index, name ->
params[name] = matchResult.groupValues[index + 1]
}
// Query-Parameter hinzufügen
parsed.queryParams.forEach { (key, value) ->
params[key] = value
}
return RouteMatch(screen = route.screen, params = params)
}
return null
}
private fun routePattern(pattern: String, screen: String): RoutePattern {
val paramNames = mutableListOf<String>()
val regexStr = pattern.replace(Regex("\\{([^}]+)\\}")) { matchResult ->
paramNames.add(matchResult.groupValues[1])
"([^/]+)"
}
return RoutePattern(
regex = Regex("^$regexStr$"),
screen = screen,
paramNames = paramNames
)
}
}
URL-Parser
In KMP gibt es kein java.net.URL im Common Code. Schreib dir einen einfachen Parser oder nimm eine Multiplatform-Bibliothek wie Ktors Url:
// commonMain/UrlParser.kt
data class ParsedUrl(
val scheme: String,
val host: String,
val path: String,
val queryParams: Map<String, String>
)
fun parseUrl(urlString: String): ParsedUrl? {
// Einfaches URL-Parsing für Deep Links
val schemeEnd = urlString.indexOf("://")
if (schemeEnd == -1) return null
val scheme = urlString.substring(0, schemeEnd)
val rest = urlString.substring(schemeEnd + 3)
val pathStart = rest.indexOf('/')
if (pathStart == -1) return ParsedUrl(scheme, rest, "/", emptyMap())
val host = rest.substring(0, pathStart)
val pathAndQuery = rest.substring(pathStart)
val queryStart = pathAndQuery.indexOf('?')
val path: String
val queryParams: Map<String, String>
if (queryStart == -1) {
path = pathAndQuery.trimEnd('/')
queryParams = emptyMap()
} else {
path = pathAndQuery.substring(0, queryStart).trimEnd('/')
queryParams = parseQueryString(pathAndQuery.substring(queryStart + 1))
}
return ParsedUrl(scheme, host, path.ifEmpty { "/" }, queryParams)
}
private fun parseQueryString(query: String): Map<String, String> {
return query.split("&")
.filter { it.contains("=") }
.associate { param ->
val (key, value) = param.split("=", limit = 2)
key to value
}
}
Für den Produktionseinsatz lohnen sich die URL-Utilities des Ktor-Clients , die auch Sonderfälle wie Percent-Encoding abdecken.
Shared Module: Action Types
Definiere typisierte Actions, damit der Plattformcode keine rohen Strings auswerten muss:
// commonMain/DeepLinkAction.kt
sealed class DeepLinkAction {
data class ViewProduct(
val productId: String,
val source: String? = null
) : DeepLinkAction()
data class ViewOffer(val offerId: String) : DeepLinkAction()
data class ApplyReferral(val referrerId: String) : DeepLinkAction()
data class Search(val query: String) : DeepLinkAction()
object OpenHome : DeepLinkAction()
}
fun RouteMatch.toAction(): DeepLinkAction {
return when (screen) {
"ProductDetail" -> DeepLinkAction.ViewProduct(
productId = params["productId"] ?: "",
source = params["ref"]
)
"OfferDetail" -> DeepLinkAction.ViewOffer(
offerId = params["offerId"] ?: ""
)
"Referral" -> DeepLinkAction.ApplyReferral(
referrerId = params["referrerId"] ?: ""
)
"Search" -> DeepLinkAction.Search(
query = params["q"] ?: ""
)
else -> DeepLinkAction.OpenHome
}
}
Umsetzung unter Android
Intents verarbeiten
// androidMain/AndroidDeepLinkHandler.kt
class AndroidDeepLinkHandler(
private val navigator: AndroidNavigator
) {
fun handleIntent(intent: Intent) {
val uri = intent.data ?: return
handleUrl(uri.toString())
}
fun handleUrl(urlString: String) {
val route = DeepLinkRouter.match(urlString)
val action = route?.toAction() ?: DeepLinkAction.OpenHome
navigator.execute(action)
}
}
Activity einrichten
// Android Activity
class MainActivity : ComponentActivity() {
private val deepLinkHandler by lazy {
AndroidDeepLinkHandler(AndroidNavigator(this))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Deep Link beim App-Start verarbeiten
deepLinkHandler.handleIntent(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
// Deep Link verarbeiten, wenn die App schon läuft
deepLinkHandler.handleIntent(intent)
}
}
Navigation unter Android
// androidMain/AndroidNavigator.kt
class AndroidNavigator(private val activity: ComponentActivity) {
fun execute(action: DeepLinkAction) {
when (action) {
is DeepLinkAction.ViewProduct -> {
// Mit Jetpack Navigation oder direktem Intent
val intent = Intent(activity, ProductActivity::class.java).apply {
putExtra("productId", action.productId)
action.source?.let { putExtra("source", it) }
}
activity.startActivity(intent)
}
is DeepLinkAction.ViewOffer -> {
val intent = Intent(activity, OfferActivity::class.java).apply {
putExtra("offerId", action.offerId)
}
activity.startActivity(intent)
}
is DeepLinkAction.ApplyReferral -> {
// Referral-Code speichern, dann navigieren
ReferralStore.save(action.referrerId)
val intent = Intent(activity, HomeActivity::class.java)
activity.startActivity(intent)
}
is DeepLinkAction.Search -> {
val intent = Intent(activity, SearchActivity::class.java).apply {
putExtra("query", action.query)
}
activity.startActivity(intent)
}
is DeepLinkAction.OpenHome -> {
val intent = Intent(activity, HomeActivity::class.java)
activity.startActivity(intent)
}
}
}
}
AndroidManifest.xml
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https"
android:host="yourdomain.com"
android:pathPrefix="/products" />
<data android:scheme="https"
android:host="yourdomain.com"
android:pathPrefix="/offers" />
<data android:scheme="https"
android:host="yourdomain.com"
android:pathPrefix="/referral" />
</intent-filter>
</activity>
Umsetzung unter iOS
Für die iOS-Seite eines KMP-Projekts hast du zwei Möglichkeiten: Du schreibst den Handler in Kotlin (iosMain) und rufst ihn aus Swift auf, oder du schreibst ihn in Swift und rufst den geteilten Kotlin-Router auf.
Option 1: Kotlin iosMain mit Aufruf aus Swift
// iosMain/IosDeepLinkHandler.kt
class IosDeepLinkHandler {
fun handleUrl(urlString: String): DeepLinkAction {
val route = DeepLinkRouter.match(urlString)
return route?.toAction() ?: DeepLinkAction.OpenHome
}
}
Aufruf aus Swift:
// AppDelegate.swift
import shared // geteiltes KMP-Framework
class AppDelegate: UIResponder, UIApplicationDelegate {
let deepLinkHandler = IosDeepLinkHandler()
func application(_ application: UIApplication,
continue userActivity: NSUserActivity,
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
guard let url = userActivity.webPageUrl else { return false }
let action = deepLinkHandler.handleUrl(urlString: url.absoluteString)
navigate(action: action)
return true
}
private func navigate(action: DeepLinkAction) {
switch action {
case let product as DeepLinkAction.ViewProduct:
// Zum Produkt-Screen navigieren
let vc = ProductViewController(productId: product.productId)
rootNavigationController?.pushViewController(vc, animated: true)
case let offer as DeepLinkAction.ViewOffer:
let vc = OfferViewController(offerId: offer.offerId)
rootNavigationController?.pushViewController(vc, animated: true)
case let referral as DeepLinkAction.ApplyReferral:
ReferralStore.shared.save(referrerId: referral.referrerId)
// Zum Home-Screen navigieren
default:
// Zum Home-Screen navigieren
break
}
}
}
Option 2: Nur Swift mit geteiltem Router
Wenn du den iOS-Navigationscode komplett in Swift halten willst, ruf einfach den Router auf:
import shared
func handleDeepLink(_ url: URL) {
guard let route = DeepLinkRouter.shared.match(urlString: url.absoluteString) else {
navigateToHome()
return
}
let action = DeepLinkActionKt.toAction(route)
// Action in Swift verarbeiten...
}
iOS Entitlements
Füge applinks:yourdomain.com zu den Associated Domains in Xcode hinzu, wie bei jedem anderen Universal-Links-Setup unter iOS.
Den geteilten Router testen
Das Shared Module kannst du mit normalen Kotlin-Tests testen:
// commonTest/DeepLinkRouterTest.kt
class DeepLinkRouterTest {
@Test
fun matchesProductUrl() {
val result = DeepLinkRouter.match(
"https://yourdomain.com/products/abc123"
)
assertNotNull(result)
assertEquals("ProductDetail", result.screen)
assertEquals("abc123", result.params["productId"])
}
@Test
fun includesQueryParameters() {
val result = DeepLinkRouter.match(
"https://yourdomain.com/products/abc123?ref=email&campaign=summer"
)
assertNotNull(result)
assertEquals("email", result.params["ref"])
assertEquals("summer", result.params["campaign"])
}
@Test
fun returnsNullForUnknownPath() {
val result = DeepLinkRouter.match(
"https://yourdomain.com/unknown/path"
)
assertNull(result)
}
@Test
fun convertToViewProductAction() {
val route = DeepLinkRouter.match(
"https://yourdomain.com/products/abc123?ref=email"
)!!
val action = route.toAction()
assertTrue(action is DeepLinkAction.ViewProduct)
assertEquals("abc123", (action as DeepLinkAction.ViewProduct).productId)
assertEquals("email", action.source)
}
@Test
fun handlesTrailingSlash() {
val result = DeepLinkRouter.match(
"https://yourdomain.com/products/abc123/"
)
assertNotNull(result)
assertEquals("abc123", result.params["productId"])
}
}
Diese Tests laufen auf allen KMP-Targets (JVM, Native, JS) und prüfen, dass die Routing-Logik überall gleich funktioniert.
Gradle-Konfiguration
Füge die Abhängigkeit zum Shared Module in beiden Plattform-Targets hinzu:
// shared/build.gradle.kts
kotlin {
androidTarget()
iosX64()
iosArm64()
iosSimulatorArm64()
sourceSets {
commonMain.dependencies {
// Für einfaches Routing brauchst du keine externen Abhängigkeiten
}
commonTest.dependencies {
implementation(kotlin("test"))
}
}
}
Für das URL-Parsing in Produktion kannst du Ktor hinzufügen:
commonMain.dependencies {
implementation("io.ktor:ktor-http:3.1.0")
}
Tolinku für KMP-Projekte
Tolinku hostet die Verifizierungsdateien für AASA und assetlinks.json und bietet Deferred Deep Linking für Nutzer, die die App erst nach dem Tippen auf einen Link installieren. Trag die Details deiner iOS- und Android-App in den Appspace-Einstellungenein, und Tolinku erzeugt die Verifizierungsdateien automatisch. Routes , ausgeliefert mit dynamische Parameter funktionieren mit jeder clientseitigen Routing-Implementierung, auch mit Shared Routern in KMP.
Kotlin-Patterns für Android findest du unter Deep Link Handling in Kotlin: moderne Android-Patterns. Mehr zu Xamarin/.NET MAUI findest du unter Xamarin Deep Linking: Cross-Platform-Setup.
Deep-Linking-Tipps direkt in Ihr Postfach
Eine E-Mail pro Woche. Kein Spam.