ios - How to convert string into NSData to pass it to BLE Device? -
i have textfield user enters text doesn't know length even, have convert hexadecimal. have done through code.
nsstring * str = @"hello world"; nsstring * hexstr = [nsstring stringwithformat:@"%@", [nsdata datawithbytes:[str cstringusingencoding:nsutf8stringencoding] length:strlen([str cstringusingencoding:nsutf8stringencoding])]]; for(nsstring * toremove in [nsarray arraywithobjects:@"<", @">", @" ", nil]) hexstr = [hexstr stringbyreplacingoccurrencesofstring:toremove withstring:@""]; nslog(@"%@", hexstr); 48656c6c6f20776f726c64
but hard parts start that. how separate every 2 hex uint8_t. because don't know length, user can write of length of string huge hexadecimal.if know length can this
nsmutabledata *concatenate = [nsmutabledata data]; uint8_t first=0x48; uint8_t second = 0x56; uint8_t third = 0x6c; uint8_t fourth = 0x6f; uint8_t fifth=0x20; uint8_t sixth=0x77; uint8_t seventh=0x6f; uint8_t eighth=0x72; uint8_t ninth=0x6c; uint8_t tenth=0x64; nsdata* 1 = [nsdata datawithbytes:(void*)&first length:sizeof(first)]; nsdata* 2 = [nsdata datawithbytes:(void*)&second length:sizeof(second)]; nsdata* 3 = [nsdata datawithbytes:(void*)&third length:sizeof(third)]; nsdata* 4 = [nsdata datawithbytes:(void*)&fourth length:sizeof(fourth)]; nsdata* 5 = [nsdata datawithbytes:(void*)&fifth length:sizeof(fifth)]; nsdata* 6 = [nsdata datawithbytes:(void*)&sixth length:sizeof(sixth)]; nsdata* 7 = [nsdata datawithbytes:(void*)&seventh length:sizeof(seventh)]; nsdata* 8 = [nsdata datawithbytes:(void*)&eighth length:sizeof(eighth)]; nsdata* 9 = [nsdata datawithbytes:(void*)&nineth length:sizeof(nineth)]; nsdata* ten = [nsdata datawithbytes:(void*)&tenth length:sizeof(tenth)]; [concatenate appenddata:one]; [concatenate appenddata:two]; [concatenate appenddata:three]; [concatenate appenddata:four]; [concatenate appenddata:five]; [concatenate appenddata:six]; [concatenate appenddata:seven]; [concatenate appenddata:eight]; [concatenate appenddata:nine]; [concatenate appenddata:ten];
but when don't know length don't know.any or clue highly appreciated.
first time should convert nsstring nsdata
nsstring* str = @"hello world"; nsdata* data = [str datausingencoding:nsutf8stringencoding];
next send data device
[discoveredperipheral writevalue:data forcharacteristic:charforvalue type:cbcharacteristicwritewithresponse];
here can send data response device or without. of course device should ready receive such data with/without response.
for understanding discoveredperipheral variable receive
-(void)centralmanager:(cbcentralmanager *)central diddiscoverperipheral:(cbperipheral *)peripheral advertisementdata:(nsdictionary *)advertisementdata rssi:(nsnumber *)rssi
charforvalue variable received in
- (void)peripheral:(cbperipheral *)peripheral diddiscovercharacteristicsforservice:(cbservice *)service error:(nserror *)error
for necessary service , characteristic.
Comments
Post a Comment