YH_ScanUtility.m
2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//
// YH_ScanUtility.m
// YH_Mall
//
// Created by Cloud on 15/4/10.
// Copyright (c) 2015年 YOHO. All rights reserved.
//
#import "YH_ScanUtility.h"
#import <UIKit/UIKit.h>
@interface YH_ScanUtility ()
@property (copy, nonatomic) NSString *scanResultString;
@property (strong, nonatomic) StringBlock scanResultBlock;
@end
@implementation YH_ScanUtility
- (instancetype)init
{
self = [super init];
if (self) {
_enableFlashLight = NO;
}
return self;
}
- (void)addScanCallBackHandle:(StringBlock)scanCallBack
{
self.scanResultBlock = scanCallBack;
}
- (void)resetCamera
{
[self setupAVCamera];
}
- (void)setupAVCamera
{
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (self.enableFlashLight) {
if ([_device lockForConfiguration:nil]) {
// if ([_device respondsToSelector:@selector(setFlashMode:)]) {
// [_device setFlashMode:AVCaptureFlashModeOn];
// }
if ([_device respondsToSelector:@selector(setTorchMode:)]) {
[_device setTorchMode:AVCaptureTorchModeOn];
}
[_device setTorchModeOnWithLevel:AVCaptureMaxAvailableTorchLevel error:nil];
[_device unlockForConfiguration];
}
}
_input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
self.output = [[AVCaptureMetadataOutput alloc]init];
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// Session
self.session = [[AVCaptureSession alloc]init];
[_session setSessionPreset:AVCaptureSessionPresetHigh];
if ([_session canAddInput:self.input]){
[_session addInput:self.input];
} else {
return;
}
if ([_session canAddOutput:self.output]){
[_session addOutput:self.output];
} else {
return;
}
// 条码类型 AVMetadataObjectTypeQRCode
_output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
self.previewLayer.frame = [[UIScreen mainScreen] bounds];
_output.rectOfInterest = CGRectMake(0, 0, (175.f+220.f)*kScreenPointScale/kScreenHeight, (190.f+220.f)*kScreenPointScale/kScreenWidth);
[_session startRunning];
}
#pragma mark -
#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
[_session stopRunning];
NSString *stringValue = nil;
if ([metadataObjects count] <= 0){
return;
}
AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
stringValue = metadataObject.stringValue;
self.scanResultBlock(stringValue,nil);
}
@end