简体   繁体   中英

How to convert String to Byte Array in iOS module of Kotlin Multiplatform project?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM