我正在使用 CoreBlueTooth API 将数据写入我们从某个硬件制造公司收到的外围设备中。根据规范,他们为我们提供了一系列特征 UUID 以将数据写入其中。一旦我们想要完成,我们需要在其中一个特征中写入 0。现在,问题是当我尝试发送字符串/整数并将它们转换为 NSData 时,它不起作用。我想我需要以那些可写特征发送字节流。有人可以帮助我如何在发送之前将我的 NSString 和 NSNumber 数据转换为字节流。以下是我尝试使用的转换代码:
- (void)writeCharactersticData:(NSDictionary *)iData toPeripheral:(CBPeripheral *)iPeripheral {
NSArray *charactersticsIDs = [NSArray arrayWithArray:iData.allKeys];
self.writeCharactersticsCount = charactersticsIDs.count;
for (CBUUID *uuid in charactersticsIDs) {
if (self.peripheralCharacterstics[uuid]) {
NSData *payload;
if ([iData[uuid] isKindOfClass:[NSNumber class]]) {
NSInteger data = ((NSNumber *)iData[uuid]).integerValue;
// int integerSize = sizeof(data);
//
// uint8_t bytes[integerSize];
//
//
// NSLog(@"Integer data = %d", data);
//
// int8_t tx = (int8_t)data;
// bytes[0] = tx;
// payload = [NSData dataWithBytes:bytes length:sizeof(data)];
payload = [NSData dataWithBytes:&data length:sizeof(data)];
} else if ([iData[uuid] isKindOfClass:[NSString class]]) {
int stringSize = sizeof(iData[uuid]);
uint8_t bytes[stringSize];
NSScanner *scanner = [NSScanner scannerWithString:iData[uuid]];
for (int i=0; i<stringSize; i++) {
unsigned int value;
[scanner scanHexInt:&value];
bytes[i] = (uint8_t)value;
}
payload = [NSData dataWithBytes:bytes length:stringSize];
// payload = [iData[uuid] dataUsingEncoding:NSUTF8StringEncoding];
}
[self.discoveredPeripheral writeValue:payload forCharacteristic:self.peripheralCharacterstics[uuid] type:CBCharacteristicWriteWithResponse];
}
}
}