Hi, how can I convert a Swift `NSData` to Kotlin `...
# multiplatform
b
Hi, how can I convert a Swift
NSData
to Kotlin
ByteArray
? Background: I’m working on a Kmp library where we need to use OS’s crypto API to encrypt data. So, in Kmp library we define an Interface
Copy code
interface MessagePackHelper {
    fun serialize(payload: String): ByteArray
}
from iOS, we need to implement this interface and set back to the Kmp library. So in Swift, we need to implement below method:
Copy code
func serialize(payload: String) -> KotlinByteArray {
        // let encyrpted = encrypt(payload) // result is NSData obect
        // todo - would like to convert NSData -> KotlinByteArray
    }
e
Copy code
fun NSData.toByteArray(): ByteArray {
    return ByteArray(length.toInt()).apply {
        usePinned {
            memcpy(it.addressOf(0), bytes, length)
        }
    }
}

fun ByteArray.toNSData(): NSData = memScoped { 
    NSData.create(bytes = allocArrayOf(this@toNSData), length = this@toNSData.size.toULong()) 
}
b
Thanks @Evegenii Khokhlov. That should be Kotlin code defined in iOS source set, isn’t it?
e
Yes, you are right, you need to
import platform.Foundation.*
and also
import platform.posix.memcpy
b
Great, I will try it out
878 Views