Abhinav Abhinav - 1 year ago 90
iOS Question

Unable to write data into hardware peripheral

I am using CoreBlueTooth API to write data into a peripheral we have received from some hardware manufacturing company. As per the specs they have given us a bunch of characteristics UUIDs to write data into. Once we want to finish we need to write 0 in one of the characteristics. Now, the problem is that when I am trying to send String/Integer and converting them into NSData then its not working. I think I need to send byte stream in those writable characteristics. Can someone help me as how can I convert my NSString & NSNumber data into byte stream before sending them. Below is my conversion code I tried with:

- (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];

Answer Source

This is not a Core Bluetooth based problem you have here.

For debugging, you could use

NSLog(@"%@", payload);

For your string to NSData conversion, your approach seems very complicated. I would suggest something simple like

NSData* payload = [iData[uuid] dataUsingEncoding:NSUTF8StringEncoding];
if (payload.length > 20)
    // handle error. most LE peripherals don't support longer values.

Another error could be that you mix ASCII 0 '0' with a binary zero '\0' when writing your value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download