<pre><code>
import "QYScanCtrl.h"
import <AVFoundation/AVFoundation.h>
import "trConst.h"
@interface QYScanCtrl ()<AVCaptureMetadataOutputObjectsDelegate,UIWebViewDelegate>
//拍攝會(huì)話
@property(nonatomic,strong)AVCaptureSession
*session;
//預(yù)覽視圖
@property(nonatomic,strong)AVCaptureVideoPreviewLayer
*preview;
@end
@implementation
QYScanCtrl
-
(void)viewDidLoad {
[superviewDidLoad];
self.view.backgroundColor= [UIColorwhiteColor];
self.title = @"防偽查詢(xún)";
//掃描
[selfscan];
}
-(void)scan{
// 攝像頭輸入設(shè)備
//捕獲設(shè)備逝慧,默認(rèn)后置攝像頭
AVCaptureDevice
*device = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
//輸入設(shè)備
AVCaptureDeviceInput
*inputDevice = [AVCaptureDeviceInputdeviceInputWithDevice:device error:&error];
// 元數(shù)據(jù)輸出對(duì)象
AVCaptureMetadataOutput
*dataOutput = [[AVCaptureMetadataOutputalloc]init];
// 拍攝會(huì)話
self.session = [[AVCaptureSession alloc]init];
// 建立通道
//先判斷是否有該設(shè)備
if ([self.session canAddInput:inputDevice])
{
[self.session addInput:inputDevice];
}else{
NSLog(@"不支持該設(shè)備");
return;
}
if ([self.session canAddOutput:dataOutput])
{
[self.session addOutput:dataOutput];
}else{
NSLog(@"不支持該設(shè)備");
return;
}
// 設(shè)置元數(shù)據(jù)輸出對(duì)象相關(guān)屬性
dataOutput.metadataObjectTypes = @[@"org.iso.QRCode"];
// 實(shí)現(xiàn)代理方法
[dataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// 開(kāi)始掃描
[self.session startRunning];
// 添加預(yù)覽視圖
AVCaptureVideoPreviewLayer
*preview = [AVCaptureVideoPreviewLayerlayerWithSession:self.session];
self.preview = preview;
//設(shè)置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];
//掃描完成加載結(jié)果頁(yè)面
NSURL*url = [NSURLURLWithString:[NSString stringWithFormat:@"%@%@%@",HTTP_HOST_URL,HTTP_H5_SCAN,result]];
NSURLRequest*request = [NSURLRequest requestWithURL:url];
[web loadRequest:request];
}
@end