原生扫描用到的几个类
、、、
@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;
、、、
按钮以及按钮事件
btn=[[UIButton alloc]initWithFrame:CGRectMake(160, 120, 100, 50)];
btn.backgroundColor=[UIColor grayColor]; [btn setTitle:@"开始扫描" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(clickbtn) forControlEvents:UIControlEventTouchUpInside];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.view addSubview:btn];
btn1=[[UIButton alloc]initWithFrame:CGRectMake(160, 210, 100, 50)];
btn1.backgroundColor=[UIColor grayColor];
[btn1 setTitle:@"扫描" forState:UIControlStateNormal];
[btn1 addTarget:self action:@selector(clickbtn1) forControlEvents:UIControlEventTouchUpInside];
[btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.view addSubview:btn1];
}
-(void)clickbtn{
BOOL isScan =[self checkAVAuthorizationStatus];
if(isScan==YES) {
NSLog(@"可以扫描");
}else {
NSLog(@"怒可以");
[btn1setEnabled:NO];
}}
-(void)clickbtn1{
[selfsetScan];
}
创建他们
-(void)setScan
{
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// Input
_input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
// Output
_output = [[AVCaptureMetadataOutput alloc]init];
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// Session
_session = [[AVCaptureSession alloc]init];
[_session setSessionPreset:AVCaptureSessionPresetHigh];
连接输入和输出
if ([_session canAddInput:self.input])
{
[_sessionaddInput:self.input];
}
if ([_session canAddOutput:self.output])
{
[_session addOutput:self.output];
}
设置条码类型
_output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
添加扫描画面
_preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
_preview.videoGravity =AVLayerVideoGravityResizeAspectFill;
_preview.frame =self.view.layer.bounds;
[self.view.layer insertSublayer:_preview atIndex:0];
开始扫描
[_session startRunning];
}
最后实现协议AVCaptureMetadataOutputObjectsDelegat
- (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputMetadataObjects:(NSArray*)metadataObjects fromConnection:(AVCaptureConnection*)connection
{
NSString*stringValue;
if([metadataObjectscount] >0){
//停止扫描 [_sessionstopRunning];
AVMetadataMachineReadableCodeObject* metadataObject = [metadataObjectsobjectAtIndex:0];
stringValue = metadataObject.stringValue;
}
}
- (BOOL)checkAVAuthorizationStatus
{
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
// NSString *tips = NSLocalizedString(@"AVAuthorization", @"您没有权限访问相机");
if(status == AVAuthorizationStatusAuthorized) {
// authorized
// [self setupCamera];
returnYES;
}else{
// [SVProgressHUD showWithStatus:tips];
returnNO;
}
}
网友评论