forked from ricardopereira/QRCodeReader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQRCodeReaderViewController.swift
More file actions
277 lines (219 loc) · 10.2 KB
/
Copy pathQRCodeReaderViewController.swift
File metadata and controls
277 lines (219 loc) · 10.2 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
//
// QRCodeReaderViewController.swift
// Smartime
//
// Created by Ricardo Pereira on 13/05/2015.
// Copyright (c) 2015 Ricardo Pereira. All rights reserved.
//
import UIKit
import AVFoundation
public typealias ResultCallback = (QRCodeReaderViewController, String) -> ()
public typealias ErrorCallback = (QRCodeReaderViewController, NSError) -> ()
public typealias CancelCallback = (QRCodeReaderViewController) -> ()
enum QRCodeReaderViewControllerErrorCodes: Int {
case UnavailableMetadataObjectType = 1
}
public class QRCodeReaderViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
private let metadataObjectTypes: [String]
public var resultCallback: ResultCallback?
public var errorCallback: ErrorCallback?
public var cancelCallback: CancelCallback?
private var avSession: AVCaptureSession?
private var avDevice: AVCaptureDevice?
private var avVideoPreviewLayer: AVCaptureVideoPreviewLayer?
private var lastCapturedString: String?
// Constants
private let fTorchLevel: Float = 0.25
private let torchLevel = 0.25
private let torchActivationDelay = 0.25
private let errorDomain = "eu.ricardopereira.QRCodeReaderViewController"
public convenience init() {
self.init(metadataObjectTypes: [AVMetadataObjectTypeQRCode])
}
public init(metadataObjectTypes: [String]) {
self.metadataObjectTypes = metadataObjectTypes
super.init(nibName: nil, bundle: nil)
self.title = "QR Code"
}
public required init(coder aDecoder: NSCoder) {
self.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
super.init(coder: aDecoder)
}
public override func viewDidLoad() {
super.viewDidLoad()
// Config
self.view.backgroundColor = UIColor.blackColor()
// Gestures
let torchGesture = UILongPressGestureRecognizer(target: self, action: Selector("handleTorchRecognizerTap:"))
torchGesture.minimumPressDuration = torchLevel
let swipeDownGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipeDown:")
swipeDownGesture.direction = .Down
self.view.addGestureRecognizer(torchGesture)
self.view.addGestureRecognizer(swipeDownGesture)
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let _ = cancelCallback {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: Selector("cancelItemSelected:"))
} else {
self.navigationItem.leftBarButtonItem = nil
}
lastCapturedString = nil
if errorCallback == nil, let _ = cancelCallback {
errorCallback = { error in
if let performCancel = self.cancelCallback {
self.avSession?.stopRunning()
performCancel(self)
}
}
}
self.avSession = AVCaptureSession()
avVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: avSession);
avVideoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill;
avVideoPreviewLayer?.frame = self.view.bounds;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
self.avDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
if let session = self.avSession, let device = self.avDevice {
// AVCaptureDevice
if device.lowLightBoostSupported && device.lockForConfiguration(nil) {
device.automaticallyEnablesLowLightBoostWhenAvailable = true
device.unlockForConfiguration()
}
session.beginConfiguration()
var error: NSError?
var input = AVCaptureDeviceInput(device: device, error: &error)
if let e = error {
println("QRCodeReaderViewController: Error getting input device: \(e)")
session.commitConfiguration()
if let performError = self.errorCallback {
dispatch_async(dispatch_get_main_queue()) {
session.stopRunning()
performError(self, e)
}
}
return
}
session.addInput(input)
let output = AVCaptureMetadataOutput()
session.addOutput(output)
for type in self.metadataObjectTypes {
// FIXME: Forced unwrap
if !contains(output.availableMetadataObjectTypes as! [String], type) {
if let performError = self.errorCallback {
dispatch_async(dispatch_get_main_queue()) {
session.stopRunning()
performError(self, NSError(domain: self.errorDomain, code: QRCodeReaderViewControllerErrorCodes.UnavailableMetadataObjectType.rawValue, userInfo: [NSLocalizedDescriptionKey : "Unable to scan object of type \(type)"]))
}
}
return
}
}
output.metadataObjectTypes = self.metadataObjectTypes
output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
session.commitConfiguration()
dispatch_async(dispatch_get_main_queue()) {
if let videoLayer = self.avVideoPreviewLayer, let conn = videoLayer.connection {
if conn.supportsVideoOrientation {
//conn.videoOrientation = videoOrientationFromDeviceOrientation(UIDevice.currentDevice().orientation);
}
}
session.startRunning()
}
}
}
self.view.layer.addSublayer(self.avVideoPreviewLayer)
}
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
avVideoPreviewLayer?.removeFromSuperlayer();
avVideoPreviewLayer = nil;
avSession = nil;
avDevice = nil;
}
public override func prefersStatusBarHidden() -> Bool {
return true
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
avVideoPreviewLayer?.bounds = self.view.bounds;
avVideoPreviewLayer?.position = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));
}
public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
// The device has already rotated, that's why this method is being called
if let videoLayer = self.avVideoPreviewLayer, let conn = videoLayer.connection {
if conn.supportsVideoOrientation {
conn.videoOrientation = self.videoOrientationFromDeviceOrientation(UIDevice.currentDevice().orientation);
}
}
}
private func videoOrientationFromDeviceOrientation(orientation: UIDeviceOrientation) -> AVCaptureVideoOrientation {
switch (orientation) {
case .Portrait:
return AVCaptureVideoOrientation.Portrait
case .LandscapeLeft:
return AVCaptureVideoOrientation.LandscapeRight
case .LandscapeRight:
return AVCaptureVideoOrientation.LandscapeLeft
case .PortraitUpsideDown:
return AVCaptureVideoOrientation.PortraitUpsideDown
default:
return AVCaptureVideoOrientation.Portrait
}
}
// MARK: UI Actions
func cancelItemSelected(sender: AnyObject) {
avSession?.stopRunning;
cancelCallback?(self);
}
func handleSwipeDown(sender: UIGestureRecognizer) {
avSession?.stopRunning;
cancelCallback?(self);
}
func handleTorchRecognizerTap(sender: UIGestureRecognizer) {
switch(sender.state) {
case UIGestureRecognizerState.Began:
turnTorchOn()
case UIGestureRecognizerState.Changed, UIGestureRecognizerState.Possible:
break
case UIGestureRecognizerState.Ended, UIGestureRecognizerState.Cancelled, UIGestureRecognizerState.Failed:
turnTorchOff()
default:
break
}
}
// MARK: Torch
func turnTorchOn() {
if let device = avDevice {
if device.hasTorch && device.torchAvailable && device.isTorchModeSupported(.On) && device.lockForConfiguration(nil) {
device.setTorchModeOnWithLevel(fTorchLevel, error: nil)
device.unlockForConfiguration()
}
}
}
func turnTorchOff() {
if let device = avDevice {
if device.hasTorch && device.torchAvailable && device.isTorchModeSupported(.Off) && device.lockForConfiguration(nil) {
device.torchMode = .Off
device.unlockForConfiguration()
}
}
}
// MARK: AVCaptureMetadataOutputObjectsDelegate
public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
var metadataStr: String?
for metadata in metadataObjects {
if contains(self.metadataObjectTypes, metadata.type) {
metadataStr = metadata.stringValue;
break
}
}
if let result = metadataStr {
if lastCapturedString != result {
lastCapturedString = result
avSession?.stopRunning()
resultCallback?(self, result)
}
}
}
}