![](/img/trans.png)
[英]How to convert Kotlin project to Kotlin Multiplatform Mobile after the project completion?
[英]How to convert String to Byte Array in iOS module of Kotlin Multiplatform project?
這是我第一次對Kotlin Multiplatform進行實驗,看來我還沒有完全掌握一些知識。
我的后端通過UDP多播中的套接字發送通知消息(我可能需要針對每個平台實現此部分,因為我認為Kotlin不會為我做這件事)。 然后,我想將此消息(以字節數組的形式)傳遞給我的通用模塊。 該模塊負責解析消息並將結果返回到平台。
為了簡化我的工作,我希望每個平台都返回test
消息的ByteArray。
這是我的common.kt
文件:
package org.kotlin.mpp.mobile
expect fun receivedEASNotification(): ByteArray
fun parseEASNotification(msg: ByteArray) {
// Use receivedEASNotification()
}
這是Android文件:
package org.kotlin.mpp.mobile
actual fun receivedEASNotification(): ByteArray {
return "test".toByteArray(Charsets.UTF_8)
}
我的問題是在iOS
部分。 我不知道如何將字符串轉換為ByteArray。 有toCharArray()
函數,但沒有toByteArray()
。 另外,還有toByte()
函數。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.