1 首先使APP獲得相機(jī)使用權(quán)限
在plist文件中用source code的方式打開,添加如下代碼:
<key>NSCameraUsageDescription</key>
<string>cameraDesciption</string>
如果沒有使應(yīng)用獲取相機(jī)使用權(quán)限,則使用過程中會(huì)崩潰。
2 判斷權(quán)限
也就是針對(duì)是否獲得相機(jī)使用權(quán)限做檢驗(yàn):
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
dispatch_async(dispatch_get_main_queue(), ^{
if (granted) {
//配置掃描view
[self loadScanView];
} else {
NSString *title = @"請(qǐng)?jiān)趇Phone的”設(shè)置-隱私-相機(jī)“選項(xiàng)中,允許App訪問你的相機(jī)";
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:@"" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
[alertView show];
}
});
}];
3 配置掃描view
- (void)loadScanView {
//1.初始化捕捉設(shè)備(AVCaptureDevice),類型為AVMediaTypeVideo
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//2.用captureDevice創(chuàng)建輸入流
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:nil];
//3.創(chuàng)建媒體數(shù)據(jù)輸出流
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
//4.實(shí)例化捕捉會(huì)話
_captureSession = [[AVCaptureSession alloc] init];
//4.1.將輸入流添加到會(huì)話
[_captureSession addInput:input];
//4.2.將媒體輸出流添加到會(huì)話中
[_captureSession addOutput:output];
//5.設(shè)置代理 在主線程里刷新
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//5.2.設(shè)置輸出媒體數(shù)據(jù)類型為QRCode
[output setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
//6.實(shí)例化預(yù)覽圖層
_videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
//7.設(shè)置預(yù)覽圖層填充方式
[_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
//8.設(shè)置圖層的frame
[_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
//9.將圖層添加到預(yù)覽view的圖層上
[_viewPreview.layer addSublayer:_videoPreviewLayer];
//10.設(shè)置掃描范圍
output.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
//10.1.掃描框
_boxView = [[UIView alloc] initWithFrame:CGRectMake(_viewPreview.bounds.size.width * 0.2, _viewPreview.bounds.size.height*0.2, _viewPreview.bounds.size.width - _viewPreview.bounds.size.width * 0.4f, _viewPreview.bounds.size.width - _viewPreview.bounds.size.width * 0.4f)];
_boxView.layer.borderColor = [UIColor redColor].CGColor;
_boxView.layer.borderWidth = 1.0;
[_viewPreview addSubview:_boxView];
_scanLayer = [[CALayer alloc] init];
_scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 1);
_scanLayer.backgroundColor = [UIColor blackColor].CGColor;
[_boxView.layer addSublayer:_scanLayer];
[self startRunning];
}
這里我們用到rectOfInterest 這個(gè)cgrect跟平時(shí)用的不一樣,在這里用的是比例來表示,也就是利用這個(gè)可以設(shè)置掃描的方框的范圍
4 開始掃描
#pragma mark 開始
- (void)startRunning {
if (self.captureSession) {
self.isReading = YES;
[self.captureSession startRunning];
_timer=[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(moveUpAndDownLine) userInfo:nil repeats: YES];
}
}
5 掃描線移動(dòng)
- (void)moveUpAndDownLine {
CGRect frame = self.scanLayer.frame;
if (_boxView.frame.size.height < self.scanLayer.frame.origin.y) {
frame.origin.y = 0;
self.scanLayer.frame = frame;
} else {
frame.origin.y += 5;
[UIView animateWithDuration:0.2 animations:^{
self.scanLayer.frame = frame;
}];
}
}
6 AVCaptureMetadataOutputObjectsDelegate
這個(gè)是里面用到的最重要的方法,在這個(gè)代理方法里我們可以獲得掃描二維碼解析出來的數(shù)據(jù),然后在里面進(jìn)行操作
#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
//判斷是否有數(shù)據(jù)
if (!_isReading) {
return;
}
if (metadataObjects.count > 0) {
_isReading = NO;
AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects[0];
NSString *result = metadataObject.stringValue;
if (self.resultBlock) {
self.resultBlock(result?:@"");
}
[self.navigationController popViewControllerAnimated:NO];
}
}
7 退出時(shí)記得關(guān)閉
#pragma mark 結(jié)束
- (void)stopRunning {
if ([_timer isValid]) {
[_timer invalidate];
_timer = nil ;
}
[self.captureSession stopRunning];
[_scanLayer removeFromSuperlayer];
[_videoPreviewLayer removeFromSuperlayer];
}