Search code examples
kotlinkotlin-multiplatformkotlin-native

How to create multicast on Kotlin/Native for ios/macos target


As the title says, in Swift, adding import Network can use NWMulticastGroup to create multicast, but Kotlin/Native for ios/macos still cannot use NWMulticastGroup after import platform.Network.* in src/appleMain. What is preventing me from using NWMulticastGroup? Or is this use case not currently supported? Thank you!

Other information:

  • kotlin: 2.0.0

  • gradle: 8.8

  • host: macOS 14.4.1

  • build.gradle.kts:

    plugins {
        alias(libs.plugins.kotlin.multiplatform) // version "2.0.0"
    }
    
    kotlin {
        listOf(
            iosX64(),
            iosArm64(),
            iosSimulatorArm64(),
    
            macosArm64(),
            macosX64(),
        ).forEach { target ->
            target.binaries.framework {
                baseName = "shared"
                isStatic = true
            }
        }
    
        sourceSets {
            commonMain.dependencies {
                implementation(libs.kotlin.coroutines)
            }
        }
    }
    

Solution

  • NWMulticastGroup is written in Swift, and Kotlin cannot interoperate with Swift yet.

    In other words, in Kotlin, you can only use the parts of Network.framework that are exposed to (Objective-)C. For example, instead of creating a NWMulticastGroup, you would need to call nw_group_descriptor_create_multicast. See the Objective-C version of the Network.framework documentation for more info. From a brief look, the APIs available to Kotlin mostly have a one-to-one correspondence with the Swift APIs - it's just that the former is a lot more "C-like".

    I also found this post, which shows the Objective-C version of some Swift code using Network.framework. This may be helpful too.