请在这里与我联系,因为这个问题并不容易解释和说出来。
我使用以下代码从USB连接条形码阅读器获取数据,扫描仪工作正常,数据按预期传入,但我的数据库查找失败,我相信它们失败了,因为我传入的数据DBLookup方法不正确,但我无法理解为什么,我认为NSLog正在帮助我显示明确的文本数据,而事实上并非如此,我仍然在进一步调试。
这是我的代码
- (void)didBarcodeDataReceive:(StarIoExtManager *)manager data:(NSData *)data {
NSLog(@"%s", __PRETTY_FUNCTION__);
NSMutableString *text = [NSMutableString stringWithString:@""];
const uint8_t *p = data.bytes;
for (int i = 0; i < data.length; i++) {
uint8_t ch = *(p + i);
[text appendFormat:@"%c", (char) ch];
}
NSLog(@"Scanned info as NSData was: %@", data); // raw NSData
//NSString *stringWithData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *stringWithData = [[NSString alloc] initWithBytes:(char *)data.bytes length:data.length encoding:NSUTF8StringEncoding];
NSLog(@"Scanned info as StringFromData was: %@", stringWithData);
NSLog(@"Scanned ch conversion is: %@", text);
int createTransactionResult = -1;
createTransactionResult = [NWBarCodeHelper createTransactionRowFromBarCode:text];
if ([NWTillHelper isDebug] == 1) {
NSLog(@"mPOP delegate holds barcode: %@", stringWithData);
if(createTransactionResult != 0) {
NSLog(@"TransactionListView:mPOPDelegate:createTransactionFrombarCode failed with errorCode %i", createTransactionResult);
}
}
}
我的调试输出显示正确的数据如下
2017-04-19 10:19:01.868198 NWMobileTill[3751:1638657] Scanned info as NSData was: <30393235 38333834 33393439 35310d0a>
2017-04-19 10:19:01.868439 NWMobileTill[3751:1638657] Scanned info as StringFromData was: 09258384394951
2017-04-19 10:19:01.868652 NWMobileTill[3751:1638657] Scanned ch conversion is: 09258384394951
2017-04-19 10:19:01.868979 NWMobileTill[3751:1638657] NWBarCodeHelper:createTransactionRowFromBarcode:barcode = 09258384394951
2017-04-19 10:19:01.875938 NWMobileTill[3751:1638657] NWBarcodeHelper:CreateTransactionRowFromBarcode: 0 or more than one row returned, basic data error, item count = 0
但正如您所看到的最后一行显示数据库查找失败,我知道该方法是正确的,因为当我使用iPhone相机扫描并将该数据传递到相同的方法时,它在同一条形码上工作得很好所以它必须是从USB扫描仪传入的字符串的东西诱骗我,但我无法理解为什么,我认为NSLog试图帮助我,但没有向我显示编码数据或什么?
答案 0 :(得分:1)
您的字符串最后包含\r\n
。看看下面的代码:
unsigned char bytes[] = {0x30, 0x39, 0x32, 0x35, 0x38, 0x33, 0x38, 0x34, 0x33, 0x39 ,0x34, 0x39, 0x35, 0x31, 0x0d, 0x0a};
NSData *data = [NSData dataWithBytes:bytes length:16];
NSString *stringWithData = [[NSString alloc] initWithBytes:(char *)data.bytes length:data.length encoding:NSUTF8StringEncoding];
NSLog(@"%@", stringWithData); // 09258384394951
NSLog(@"%lu", (unsigned long)[stringWithData length]); // 16
// remove \r\n at the end which gets added by the barcode scanner
NSString *string = [stringWithData stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"%@", string); // 09258384394951
NSLog(@"%lu", (unsigned long)[string length]); // 14
或者,如果您想使用appendFormat
方法,只需检查它是否为有效数字,然后再将其添加到字符串中,而不是稍后将其删除。