Reputation: 53610
This is my first experiment of Kotlin Multiplatform and it seems that I've not got some pieces completely.
My backend sends a notification message via socket in UDP Multicast (I probably need to implement this part per platform as I don't think Kotlin does it for me). Then I want to pass this message (which in form of Byte Array) to my common module. This module is responsible to parse the message and return result to platforms.
Just to simplify my work, I want each platform to return ByteArray of test
message.
This is my common.kt
file:
package org.kotlin.mpp.mobile
expect fun receivedEASNotification(): ByteArray
fun parseEASNotification(msg: ByteArray) {
// Use receivedEASNotification()
}
This is Android file:
package org.kotlin.mpp.mobile
actual fun receivedEASNotification(): ByteArray {
return "test".toByteArray(Charsets.UTF_8)
}
My problem is in iOS
part. I can't realize how to convert string to ByteArray. There is toCharArray()
function but not toByteArray()
. Also, there is toByte()
function.
actual fun receivedEASNotification(): ByteArray {
return "test".toByteArray() // There is no such a function for iOS.
}
Upvotes: 1
Views: 2101
Reputation: 307
import Foundation
// An input string.
let name = "perls"
// Get the String.UTF8View.
let bytes = name.utf8
print(bytes)
// Get an array from the UTF8View.
// ... This is a byte array of character data.
var buffer = [UInt8](bytes)
// Change the first byte in the byte array.
// The byte array is mutable.
buffer[0] = buffer[0] + UInt8(1)
print(buffer)
// Get a string from the byte array.
if let result = String(bytes: buffer, encoding: NSASCIIStringEncoding) {
print(result)
}
OUTPUT:
perls
[113, 101, 114, 108, 115]
qerls
Upvotes: 0