-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathDYQRCodeDecoderViewController.m
More file actions
413 lines (348 loc) · 18.9 KB
/
DYQRCodeDecoderViewController.m
File metadata and controls
413 lines (348 loc) · 18.9 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//
// DYQRCodeDecoderViewController.m
// QRCode-Decoder
//
// Created by Dwarven on 16/7/5.
// Copyright © 2016 Dwarven. All rights reserved.
//
#import "DYQRCodeDecoderViewController.h"
#import <AVFoundation/AVFoundation.h>
#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height
@interface DYQRCodeDecoderViewController () <
AVCaptureMetadataOutputObjectsDelegate,
UINavigationControllerDelegate,
UIImagePickerControllerDelegate> {
void(^_completion)(BOOL, NSString *);
NSMutableArray *_observers;
UIView *_viewPreview;
UIImageView * _lineImageView;
CGRect _lineRect0;
CGRect _lineRect1;
}
@property (nonatomic, strong, readwrite) UIBarButtonItem * leftBarButtonItem;
@property (nonatomic, strong, readwrite) UIBarButtonItem * rightBarButtonItem;
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@property (nonatomic) BOOL isReading;
@end
@implementation DYQRCodeDecoderViewController
- (void)dealloc{
[self cleanNotifications];
_observers = nil;
_viewPreview = nil;
_lineImageView = nil;
_completion = NULL;
self.imagePicker = nil;
self.captureSession = nil;
self.videoPreviewLayer = nil;
self.leftBarButtonItem = nil;
self.rightBarButtonItem = nil;
self.frameImage = nil;
self.lineImage = nil;
self.navigationBarTintColor = nil;
}
- (void)setupNotifications{
if (!_observers) {
_observers = [NSMutableArray array];
}
NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
__weak DYQRCodeDecoderViewController * SELF = self;
id o;
o = [center addObserverForName:UIApplicationDidEnterBackgroundNotification
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
[SELF.imagePicker dismissViewControllerAnimated:NO completion:NULL];
[SELF cancel];
}];
[_observers addObject:o];
}
- (void)cleanNotifications{
for (id o in _observers) {
[[NSNotificationCenter defaultCenter] removeObserver:o];
}
[_observers removeAllObjects];
}
- (id)initWithCompletion:(void (^)(BOOL, NSString *))completion{
self = [super init];
if (self) {
_needsScanAnnimation = YES;
_completion = completion;
_frameImage = [UIImage imageNamed:@"img_animation_scan_pic" inBundle:[NSBundle bundleForClass:[DYQRCodeDecoderViewController class]] compatibleWithTraitCollection:nil];
_lineImage = [UIImage imageNamed:@"img_animation_scan_line" inBundle:[NSBundle bundleForClass:[DYQRCodeDecoderViewController class]] compatibleWithTraitCollection:nil];
_leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Cancel"
style:UIBarButtonItemStylePlain
target:self
action:@selector(cancel)];
_rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Album"
style:UIBarButtonItemStylePlain
target:self
action:@selector(pickImage)];
}
return self;
}
- (void)viewDidLayoutSubviews{
[super viewDidLayoutSubviews];
[self startReading];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
if (_needsScanAnnimation) {
[UIView animateWithDuration:2 delay:0 options:UIViewAnimationOptionRepeat animations:^{
[_lineImageView setFrame:_lineRect1];
} completion:^(BOOL finished) {
[_lineImageView setFrame:_lineRect0];
}];
}
}
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[self startReading];
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[self stopReading];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self setupNotifications];
_imagePicker = [[UIImagePickerController alloc] init];
_imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
_imagePicker.delegate = self;
if (_navigationBarTintColor) {
if (self.navigationController) {
self.navigationController.navigationBar.tintColor = _navigationBarTintColor;
}
_imagePicker.navigationBar.tintColor =_navigationBarTintColor;
}
// Initially make the captureSession object nil.
_captureSession = nil;
// Set the initial value of the flag to NO.
_isReading = NO;
[self.navigationItem setLeftBarButtonItem:_leftBarButtonItem];
[self.navigationItem setRightBarButtonItem:_rightBarButtonItem];
_viewPreview = [[UIView alloc] init];
[self.view addSubview:_viewPreview];
[_viewPreview setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_viewPreview
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_viewPreview
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_viewPreview
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_viewPreview
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:0.0]];
if (_needsScanAnnimation) {
UIView * scanView = [[UIView alloc] init];
[scanView setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.7]];
[self.view addSubview:scanView];
[scanView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:scanView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:_viewPreview
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:scanView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:_viewPreview
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:scanView
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:_viewPreview
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:scanView
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:_viewPreview
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:0.0]];
CGFloat frameWidth = SCREEN_WIDTH * 2 / 3;
//create path
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
[path appendPath:[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(SCREEN_WIDTH / 6, SCREEN_HEIGHT / 2 - SCREEN_WIDTH / 3, frameWidth, frameWidth) cornerRadius:0] bezierPathByReversingPath]];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = path.CGPath;
[scanView.layer setMask:shapeLayer];
UIImageView * imageView = [[UIImageView alloc] init];
[imageView setBackgroundColor:[UIColor clearColor]];
[imageView setImage:_frameImage];
[self.view addSubview:imageView];
[imageView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[imageView(==%f)]", frameWidth]
options:0
metrics:0
views:@{@"imageView":imageView}]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:[imageView(==%f)]", frameWidth]
options:0
metrics:0
views:@{@"imageView":imageView}]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:imageView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:_viewPreview
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:imageView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:_viewPreview
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0.0]];
_lineImageView = [[UIImageView alloc] init];
CGFloat lineHeight = frameWidth * _lineImage.size.height / _lineImage.size.width;
_lineRect0 = CGRectMake(0, 0, frameWidth, lineHeight);
_lineRect1 = CGRectMake(0, frameWidth - lineHeight, frameWidth, lineHeight);
[_lineImageView setFrame:_lineRect0];
[_lineImageView setImage:_lineImage];
[imageView addSubview:_lineImageView];
}
}
- (void)cancel{
[self dismissViewControllerAnimated:NO completion:NULL];
}
- (void)pickImage{
[self presentViewController:_imagePicker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
[picker dismissViewControllerAnimated:NO completion:NULL];
CIContext *context = [CIContext contextWithOptions:nil];
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode
context:context
options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}];
CIImage *cgImage = [CIImage imageWithCGImage:image.CGImage];
NSArray *features = [detector featuresInImage:cgImage];
CIQRCodeFeature *feature = [features firstObject];
NSString *result = feature.messageString;
if (_completion) {
_completion(result != nil, result);
}
[self dealWithResult:result];
[self cancel];
}
- (void)start {
[self startReading];
}
- (void)stop {
[self stopReading];
}
- (void)dealWithResult:(NSString *)result {
}
#pragma mark - Private method implementation
- (void)startReading {
if (!_isReading) {
NSError *error;
// Get an instance of the AVCaptureDevice class to initialize a device object and provide the video
// as the media type parameter.
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// Get an instance of the AVCaptureDeviceInput class using the previous device object.
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
if (input) {
// Initialize the captureSession object.
_captureSession = [[AVCaptureSession alloc] init];
// Set the input device on the capture session.
[_captureSession addInput:input];
// Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
[_captureSession addOutput:captureMetadataOutput];
// Create a new serial dispatch queue.
dispatch_queue_t dispatchQueue;
dispatchQueue = dispatch_queue_create("myQueue", NULL);
[captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
[captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
// Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
_videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
[_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
[_viewPreview.layer addSublayer:_videoPreviewLayer];
// Start video capture.
[_captureSession startRunning];
_isReading = !_isReading;
} else {
// If any error occurs, simply log the description of it and don't continue any more.
NSLog(@"%@", [error localizedDescription]);
return;
}
}
}
- (void)stopReading {
if (_isReading) {
// Stop video capture and make the capture session object nil.
[_captureSession stopRunning];
_captureSession = nil;
// Remove the video preview layer from the viewPreview view's layer.
[_videoPreviewLayer removeFromSuperlayer];
_isReading = !_isReading;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - AVCaptureMetadataOutputObjectsDelegate method implementation
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
// Check if the metadataObjects array is not nil and it contains at least one object.
if (metadataObjects != nil && [metadataObjects count] > 0) {
// Get the metadata object.
AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
// If the found metadata is equal to the QR code metadata then update the status label's text,
// stop reading and change the bar button item's title and the flag's value.
// Everything is done on the main thread.
void(^block)() = ^(void) {
[self stopReading];
[self cancel];
if (![metadataObj stringValue] || [[metadataObj stringValue] length] == 0) {
if (_completion) {
_completion(NO, nil);
}
[self dealWithResult:nil];
} else {
if (_completion) {
_completion(YES, [metadataObj stringValue]);
}
[self dealWithResult:[metadataObj stringValue]];
}
};
if ([NSThread isMainThread]) {
block();
} else {
dispatch_sync(dispatch_get_main_queue(), ^{
block();
});
}
}
}
}
@end