Fighting with a Kotlin Multiplatform project I have ended with the problem of needing to work with NsData
on my iOS platform from the sharedModule
working with Kotlin Native.
Because of this, I need to transform objectiveC NsData
to Kotlin ByteArray
and way back. How can I do this?
To convert a byte array to string in Kotlin, use String() constructor. String() constructor can take a Byte Array as argument and return a new string formed with the bytes in the given array.
Creates a new array of the specified size, where each element is calculated by calling the specified init function. Creates a new array of the specified size, with all elements initialized to zero.
To create a Byte Array in Kotlin, use arrayOf() function. arrayOf() function creates an array of specified type and given elements.
NsData to ByteArray
actual typealias ImageBytes = NSData
actual fun ImageBytes.toByteArray(): ByteArray = ByteArray([email protected]()).apply {
usePinned {
memcpy(it.addressOf(0), [email protected], [email protected])
}
}
ByteArray to NsData
actual fun ByteArray.toImageBytes(): ImageBytes? = memScoped {
val string = NSString.create(string = [email protected]())
return string.dataUsingEncoding(NSUTF8StringEncoding)
}
ByteArray to NsData different way
actual fun ByteArray.toImageBytes() : ImageBytes = memScoped {
NSData.create(bytes = allocArrayOf(this@toImageBytes),
length = [email protected]())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With