IOS Core Bluetooth : Writing NSData for Characteristic

后端 未结 5 1057
花落未央
花落未央 2021-02-11 01:48

I am using the following code to write the 0xDE value for a Bluetooth Caracteristic (Reset Device) using the IOS Core Bluetooth :

...
NSData *bytes = [@\"0xDE\"          


        
5条回答
  •  轮回少年
    2021-02-11 02:11

    This code will fix the problem :

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

    dataWithHexString implementation :

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

提交回复
热议问题