본문으로 건너뛰기
엔지니어링 · · 7분 분량

Kotlin Multiplatform(KMP)으로 딥 링킹 구현하기

작성자 Tolinku 팀
|
Kotlin Multiplatform(KMP)에서 딥 링킹 구현하기

Kotlin Multiplatform(KMP)을 쓰면 플랫폼별 UI와 API는 그대로 두고 비즈니스 로직만 iOS와 Android가 공유할 수 있어요. 딥 링크 처리도 이 구조에 잘 맞아요: URL 파싱과 라우트 매칭은 순수 로직이라 공유하고, URL 수신과 화면 이동은 플랫폼별로 처리하면 돼요. 이 글에서는 KMP로 공유 딥 링크 라우터를 만드는 과정을 차근차근 살펴봐요.

Android 전용 딥 링크 패턴은 다음 글을 참고하세요: Kotlin 딥 링크 처리: 최신 Android 패턴. 크로스 플랫폼 개요는 다음 글을 참고하세요: 2026년 크로스 플랫폼 딥 링킹 가이드.

아키텍처

KMP 프로젝트에서는 expect/actual 선언으로 플랫폼별 코드를 작성해요. 딥 링킹은 이렇게 나눠요:

  • 공유 모듈 (commonMain): URL 파싱, 라우트 매칭, 파라미터 추출
  • Android (androidMain): 인텐트 처리, Activity 내비게이션
  • iOS (iosMain): 유니버설 링크 처리, UIKit/SwiftUI 내비게이션
commonMain/
  DeepLinkRouter.kt       // 라우트 매칭 로직
  DeepLinkAction.kt       // 액션 타입
  UrlParser.kt            // URL 파싱 유틸리티

androidMain/
  AndroidDeepLinkHandler.kt   // Intent → 액션
  AndroidNavigator.kt         // Activity/Fragment 내비게이션

iosMain/
  IosDeepLinkHandler.kt       // NSUserActivity → 액션
  IosNavigator.kt             // UIKit 내비게이션

공유 모듈: 라우트 매칭

라우트 정의

// 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]
            }

            // 쿼리 파라미터 추가
            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 파서

KMP의 공통 코드에서는 java.net.URL 을 쓸 수 없어요. 간단한 파서를 직접 만들거나 다음과 같은 멀티플랫폼 라이브러리를 사용하세요: Ktor의 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? {
    // 딥 링크용 기본 URL 파싱
    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
        }
}

프로덕션에서는 Ktor 클라이언트 URL 유틸리티 를 쓰는 것도 고려해 보세요. 퍼센트 인코딩 같은 엣지 케이스까지 처리해 줘요.

공유 모듈: 액션 타입

플랫폼 코드가 원시 문자열을 직접 해석하지 않아도 되도록 타입이 있는 액션을 정의하세요:

// 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
    }
}

Android 구현

인텐트 처리

// 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 설정

// Android Activity
class MainActivity : ComponentActivity() {
    private val deepLinkHandler by lazy {
        AndroidDeepLinkHandler(AndroidNavigator(this))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 앱 실행 시 들어온 딥 링크 처리
        deepLinkHandler.handleIntent(intent)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        // 앱이 이미 실행 중일 때 들어온 딥 링크 처리
        deepLinkHandler.handleIntent(intent)
    }
}

Android 내비게이션

// androidMain/AndroidNavigator.kt

class AndroidNavigator(private val activity: ComponentActivity) {
    fun execute(action: DeepLinkAction) {
        when (action) {
            is DeepLinkAction.ViewProduct -> {
                // Jetpack Navigation 또는 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 -> {
                // 추천 코드를 저장한 뒤 이동
                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>

iOS 구현

KMP 프로젝트의 iOS 쪽은 두 가지 방법이 있어요. 핸들러를 Kotlin으로 작성하고(iosMain) Swift에서 호출하거나, Swift로 작성해서 공유 Kotlin 라우터를 호출하는 방법이에요.

방법 1: Kotlin iosMain + Swift에서 호출

// iosMain/IosDeepLinkHandler.kt

class IosDeepLinkHandler {
    fun handleUrl(urlString: String): DeepLinkAction {
        val route = DeepLinkRouter.match(urlString)
        return route?.toAction() ?: DeepLinkAction.OpenHome
    }
}

Swift에서 호출하는 코드:

// AppDelegate.swift
import shared // KMP 공유 프레임워크

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:
            // 상품 화면으로 이동
            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)
            // 홈으로 이동

        default:
            // 홈으로 이동
            break
        }
    }
}

옵션 2: Swift 전용 + 공유 라우터

iOS 내비게이션 코드를 전부 Swift로 두고 싶다면 라우터만 호출하면 돼요:

import shared

func handleDeepLink(_ url: URL) {
    guard let route = DeepLinkRouter.shared.match(urlString: url.absoluteString) else {
        navigateToHome()
        return
    }

    let action = DeepLinkActionKt.toAction(route)
    // Swift에서 action 처리...
}

iOS 엔타이틀먼트

Xcode의 Associated Domains에 applinks:yourdomain.com 항목을 추가하세요. 일반적인 iOS Universal Links 설정과 똑같아요.

공유 라우터 테스트

공유 모듈은 일반 Kotlin 테스트로 테스트할 수 있어요:

// 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"])
    }
}

이 테스트는 모든 KMP 타깃(JVM, Native, JS)에서 실행되니까 라우팅 로직이 어디서나 똑같이 동작하는지 확인할 수 있어요.

Gradle 설정

두 플랫폼 타깃 모두에 공유 모듈 의존성을 추가하세요:

// shared/build.gradle.kts
kotlin {
    androidTarget()
    iosX64()
    iosArm64()
    iosSimulatorArm64()

    sourceSets {
        commonMain.dependencies {
            // 기본 라우팅에는 외부 의존성이 필요 없음
        }
        commonTest.dependencies {
            implementation(kotlin("test"))
        }
    }
}

프로덕션용 URL 파싱이 필요하면 Ktor를 추가할 수 있어요:

commonMain.dependencies {
    implementation("io.ktor:ktor-http:3.1.0")
}

KMP 프로젝트를 위한 Tolinku

Tolinku 는 AASA와 assetlinks.json 검증 파일을 호스팅하고, 링크를 탭한 뒤 앱을 설치한 사용자를 위해 디퍼드 딥 링킹 을 제공해요. iOS와 Android 앱 정보를 Appspace 설정에서 입력하면 Tolinku가 검증 파일을 자동으로 생성해요. 라우트 이고, 백 스택에는 동적 파라미터 는 KMP 공유 라우터를 포함해 어떤 클라이언트 측 라우팅 구현과도 함께 쓸 수 있어요.

Android Kotlin 패턴은 다음 글을 참고하세요: Kotlin 딥 링크 처리: 최신 Android 패턴. Xamarin/.NET MAUI는 다음 글을 참고하세요: Xamarin 딥 링킹: 크로스 플랫폼 설정.

딥 링킹 팁을 메일로 받아 보세요

일주일에 한 번만 보내요. 스팸은 없어요.

앱에 딥 링킹을 추가해 볼까요?

유니버설 링크, 앱 링크, 디퍼드 딥 링킹, 분석을 몇 분 만에 설정할 수 있어요. 무료로 시작하세요.