IOS核心蓝牙:编写特性的NSData

我正在使用以下代码来使用IOS Core Bluetooth为Bluetooth Caracteristic(Reset Device)写入0xDE值:

... NSData *bytes = [@"0xDE" dataUsingEncoding:NSUTF8StringEncoding]; [peripheral writeValue:bytes forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse]; ... 

在我的代码中有任何错误,因为值不正确写入?

尝试使用单字节值的数组来创build数据。

 const uint8_t bytes[] = {0xDE}; NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)]; 

这是创build任意常量数据的有用方法。 对于更多的字节,

 const uint8_t bytes[] = {0x01,0x02,0x03,0x04,0x05}; NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)]; 

如果你想创build数据发送使用variables,我会build议使用NSMutableData并追加所需的字节。 它不是很漂亮,但是很容易阅读/理解,特别是当你在embedded的一面上匹配一个压缩的结构时。 下面的例子来自一个BLE项目,我们正在制作一个简单的通信协议。

 NSMutableData *data = [[NSMutableData alloc] init]; //pull out each of the fields in order to correctly //serialize into a correctly ordered byte stream const uint8_t start = PKT_START_BYTE; const uint8_t bitfield = (uint8_t)self.bitfield; const uint8_t frame = (uint8_t)self.frameNumber; const uint8_t size = (uint8_t)self.size; //append the individual bytes to the data chunk [data appendBytes:&start length:1]; [data appendBytes:&bitfield length:1]; [data appendBytes:&frame length:1]; [data appendBytes:&size length:1]; 

Swift 3.0:如果有人想知道Swift的格式稍微不同,因为writeValue可以从数组中获得计数。

 let value: UInt8 = 0xDE let data = Data(bytes: [value]) peripheral.writeValue(data, for: characteristic, type: .withResponse) 

实际上,在这里做的是将string“0xDE”写入特征。 如果你想使用二进制/八进制符号,你需要远离string。

 int integer = 0xDE; NSData *data = [[NSData alloc] initWithBytes:&integer length:sizeof(integer)]; [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse]; 

bensarz的答案几乎是正确的。 除了一件事:你不应该使用sizeof(int)作为NSData的长度。 int的大小是4或8个字节(取决于体系结构)。 如果您想发送1个字节,请改用uint8_tByte

 uint8_t byteToWrite = 0xDE; NSData *data = [[NSData alloc] initWithBytes:&byteToWrite length:sizeof(&byteToWrite)]; [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse]; 

还可以使用int作为variables的types,但是必须初始化长度为1的NSData

这段代码将解决这个问题:

 NSData * data = [self dataWithHexString: @"DE"]; [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse]; 

dataWithHexString实现:

 - (NSData *)dataWithHexString:(NSString *)hexstring { NSMutableData* data = [NSMutableData data]; int idx; for (idx = 0; idx+2 <= hexstring.length; idx+=2) { NSRange range = NSMakeRange(idx, 2); NSString* hexStr = [hexstring substringWithRange:range]; NSScanner* scanner = [NSScanner scannerWithString:hexStr]; unsigned int intValue; [scanner scanHexInt:&intValue]; [data appendBytes:&intValue length:1]; } return data; }