<pre><code>
import "QYScanCtrl.h"
import <AVFoundation/AVFoundation.h>
import "trConst.h"
@interface QYScanCtrl ()<AVCaptureMetadataOutputObjectsDelegate,UIWebViewDelegate>
//拍摄会话
@property(nonatomic,strong)AVCaptureSession
*session;
//预览视图
@property(nonatomic,strong)AVCaptureVideoPreviewLayer
*preview;
@end
@implementation
QYScanCtrl
-
(void)viewDidLoad {
[superviewDidLoad];
self.view.backgroundColor= [UIColorwhiteColor];
self.title = @"防伪查询";
//扫描
[selfscan];
}
-(void)scan{
// 摄像头输入设备
//捕获设备,默认后置摄像头
AVCaptureDevice
*device = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
//输入设备
AVCaptureDeviceInput
*inputDevice = [AVCaptureDeviceInputdeviceInputWithDevice:device error:&error];
// 元数据输出对象
AVCaptureMetadataOutput
*dataOutput = [[AVCaptureMetadataOutputalloc]init];
// 拍摄会话
self.session = [[AVCaptureSession alloc]init];
// 建立通道
//先判断是否有该设备
if ([self.session canAddInput:inputDevice])
{
[self.session addInput:inputDevice];
}else{
NSLog(@"不支持该设备");
return;
}
if ([self.session canAddOutput:dataOutput])
{
[self.session addOutput:dataOutput];
}else{
NSLog(@"不支持该设备");
return;
}
// 设置元数据输出对象相关属性
dataOutput.metadataObjectTypes = @[@"org.iso.QRCode"];
// 实现代理方法
[dataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// 开始扫描
[self.session startRunning];
// 添加预览视图
AVCaptureVideoPreviewLayer
*preview = [AVCaptureVideoPreviewLayerlayerWithSession:self.session];
self.preview = preview;
//设置frame
preview.frame = self.view.bounds;
//添加到view图层
[self.view.layer addSublayer:preview];
}
pragma mark --代理方法
-(void)captureOutput:(AVCaptureOutput*)captureOutput didOutputMetadataObjects:(NSArray
)metadataObjects fromConnection:(AVCaptureConnection)connection{
if(metadataObjects != nil&& [metadataObjects count] > 0) {
AVMetadataMachineReadableCodeObject*metadataObj = [metadataObjects objectAtIndex:0];
NSString *result;
if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode])
{
result = metadataObj.stringValue;
} else {
NSLog(@"不是二维码");
}
//扫描完成,停止扫描
[self.session stopRunning];
[self.preview removeFromSuperlayer];
self.preview = nil;
[self scanResult:result];
}
}
-(void)scanResult:(NSString*)result{
UIWebView*web = [[UIWebViewalloc]initWithFrame:CGRectMake(0, 64, screenW, screenH)];
[self.view addSubview:web];
//扫描完成加载结果页面
NSURL*url = [NSURLURLWithString:[NSString stringWithFormat:@"%@%@%@",HTTP_HOST_URL,HTTP_H5_SCAN,result]];
NSURLRequest*request = [NSURLRequest requestWithURL:url];
[web loadRequest:request];
}
@end
网友评论