嗨,我知道很多人已经知道如何做到但是请帮助我,因为我是快速编程的初学者。
请考虑此代码并帮助我进行更改
//我的阅读代码
let ReceiveData = rxCharacteristic?.value
if let ReceiveData = ReceiveData {
let ReceivedNoOfBytes = ReceiveData.count
myByteArray = [UInt8](repeating: 0, count: ReceivedNoOfBytes)
(ReceiveData as NSData).getBytes(&myByteArray, length: ReceivedNoOfBytes)
print("Data Received ",myByteArray)
}
//现在我将它们存储在一些局部变量中,如下面的
let b0 = myByteArray[0]
let b0 = myByteArray[1]
let b2 = myByteArray[2]
let b3 = myByteArray[3]
//现在我想插入一些来自文本框的数据
var tb1 = textbox1.text
var b1 = tb1.flatMap{UInt8(String($0))}
var tb2 = textbox2.text
var b2 = tb2.flatMap{UInt8(String($0))}
//现在我正在使用下面的功能块
编写所有数据let Transmitdata = NSData(bytes: bytes, length: bytes.count)
peripheral.writeValue(Transmitdata as Data, for: txCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
print("Data Sent",Transmitdata)
这里我当前正在类声明下创建一个新的字节数组并分配接收到的字节数组。如下所示
class Example:UIViwecontroller{
var storebytes: [UInt8]()
func somefunc(){
storebytes = myByteArray
}
然后尝试将我的文本框数据交换到myByteArray中前两个位置的位置,然后将其传递给transmitdata。
有没有简单的方法呢?就像在我需要的地方插入字节,然后将其传递给传输?
我尝试过使用像
这样的方法bytes.insert(new data,at: index)
但它给了我一个超出范围的指数。有人知道更好的方法吗?
答案 0 :(得分:3)
在Swift 3+ Data
中可以用作包含UInt8
个对象的集合类型。
拥有Data
String
个对象
let hello = Data("hello".utf8)
您可以使用
将其转换为[UInt8]
let hello1 = [UInt8](hello)
并返回Data
let hello2 = Data(hello1)
Data
提供所有操作API,例如append
,insert
,remove
实际上你不需要[UInt8]
。给定两个字符串Data
个对象
var hello = Data("Hello !".utf8)
let world = Data("world".utf8)
您可以在world
hello
hello.insert(contentsOf: world, at: 6)
print(String(data: hello, encoding: .utf8)!) // "Hello world!"
然后获取一系列数据
let rangeOfWorld = Data(hello[6...11])
print(String(data: rangeOfWorld, encoding: .utf8)!) // "world!"