Send hexString Data through UDP

71 Views Asked by At

I'm developing an iOS app. I've come across a problem.

I am trying to send a hexString data through UDP to an wifi camera, which will response while getting correct data. My code is shown below. However I can't get any response from my wifi camera. (I'm using https://github.com/robbiehanson/CocoaAsyncSocket)

NSString *sendMsg = @"6745000005000000000000000000000000000000000000001400000067450000140000000A"; 
NSData *bytes = [sendMsg dataUsingEncoding:NSUTF16BigEndianStringEncoding]; 
NSString *host = @"255.255.255.255"; 
[self.udpSocket sendData:bytes toHost:host port:ListenPort withTimeout:-1 tag:1];

Beside, I've try send my data through PacketSender (an app can send UDP data), which has a correct response.

enter image description here

1

There are 1 best solutions below

1
Michael Li On

Problem has been solved. The problem is while converting NSString to NSData. It's hex string which need to convert to NSData. Below is my code which works.

- (NSData *)dataFromHexString:(NSString *)hexString {
    NSAssert((hexString.length > 0) && (hexString.length % 2 == 0), @"hexString.length mod 2 != 0");
    NSMutableData *data = [[NSMutableData alloc] init];
    for (NSUInteger i=0; i<hexString.length; i+=2) {
        NSRange tempRange = NSMakeRange(i, 2);
        NSString *tempStr = [hexString substringWithRange:tempRange];
        NSScanner *scanner = [NSScanner scannerWithString:tempStr];
        unsigned int tempIntValue;
        [scanner scanHexInt:&tempIntValue];
        [data appendBytes:&tempIntValue length:1];
    }

return data;}