赞
踩
ZXing库是一个专门用来解析多种二维码和条形码(包括包括 QR Code、Aztec Code、UPC、EAN、Code 39、Code 128等)的开源性质的处理库,而ZingObjC库是它的一个移植版本。由于博主还没有真机进行调试,所以舍去了使用摄像头的一些方法,仅实现其最终识别结果的方法。
使用ZXingObjC库完整的步骤分为以下六步:
#import <ZXingObjC/ZXingObjC.h>
self.capture = [[ZXCapture alloc] init]; self.capture.delegate = self;
self.capture.layer.frame = self.view.bounds; [self.view.layer addSublayer:self.capture.layer];
[self.capture start];
- (void)captureResult:(ZXCapture *)capture result:(ZXResult *)result { if (result) { NSString *contents = result.text; // 处理扫描到的内容 } }
这里我是用来实现识别以图片形式传入的条形码
实现解码的步骤总共分为以下这几步:
- (NSString*)recognizeBarcodeInImage:(UIImage *)image { CGImageRef cgImage = image.CGImage; ZXLuminanceSource *source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:cgImage]; ZXBinaryBitmap *bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]]; NSError *error = nil; ZXDecodeHints *hints = [ZXDecodeHints hints]; ZXMultiFormatReader *reader = [ZXMultiFormatReader reader]; ZXResult *result = [reader decode:bitmap hints:hints error:&error]; if (result) { NSString *barcodeValue = result.text; NSLog(@"扫描到的条形码: %@", barcodeValue); } else { NSLog(@"条形码识别出错: %@", error); } return result.text; }
下面是用解码的信息进行简单的网络请求
- (void)networkGetBarcodeData:(NSString*)querysData { NSString *encodedString = [querysData stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; NSString *urlString = [NSString stringWithFormat:@"此处为API接口/%@", encodedString]; NSURL* url = [NSURL URLWithString:urlString]; NSURLRequest* request = [NSURLRequest requestWithURL:url]; NSURLSession* session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable body , NSURLResponse * _Nullable response, NSError * _Nullable error) { if (error == nil) { NSString *bodyString = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding]; NSDictionary *bodyDictionary = [NSJSONSerialization JSONObjectWithData:body options:kNilOptions error:nil]; NSDictionary* dataDictionary = bodyDictionary[@"data"]; //打印应答中的body NSLog(@"Response body: %@" , bodyString); NSString* brand = dataDictionary[@"trademark"]; NSString* name = dataDictionary[@"goodsName"]; NSLog(@"brand:%@", brand); NSLog(@"name:%@", name); NSString* medicineName = [NSString stringWithFormat:@"%@", name]; self.myBarcodeValue = medicineName; dispatch_async(dispatch_get_main_queue(), ^{ self.medicineLabel.text = self.myBarcodeValue; }); } else { NSLog(@"错误是%@",error); } }]; [task resume]; }
运行结果如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。