-
Notifications
You must be signed in to change notification settings - Fork 784
/
Copy pathQRScanner.swift
491 lines (438 loc) · 18.7 KB
/
QRScanner.swift
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
import Foundation
import AVFoundation
@objc(QRScanner)
class QRScanner : CDVPlugin, AVCaptureMetadataOutputObjectsDelegate {
class CameraView: UIView {
var videoPreviewLayer:AVCaptureVideoPreviewLayer?
func interfaceOrientationToVideoOrientation(_ orientation : UIInterfaceOrientation) -> AVCaptureVideoOrientation {
switch (orientation) {
case UIInterfaceOrientation.portrait:
return AVCaptureVideoOrientation.portrait;
case UIInterfaceOrientation.portraitUpsideDown:
return AVCaptureVideoOrientation.portraitUpsideDown;
case UIInterfaceOrientation.landscapeLeft:
return AVCaptureVideoOrientation.landscapeLeft;
case UIInterfaceOrientation.landscapeRight:
return AVCaptureVideoOrientation.landscapeRight;
default:
return AVCaptureVideoOrientation.portraitUpsideDown;
}
}
override func layoutSubviews() {
super.layoutSubviews();
if let sublayers = self.layer.sublayers {
for layer in sublayers {
layer.frame = self.bounds;
}
}
self.videoPreviewLayer?.connection?.videoOrientation = interfaceOrientationToVideoOrientation(UIApplication.shared.statusBarOrientation);
}
func addPreviewLayer(_ previewLayer:AVCaptureVideoPreviewLayer?) {
previewLayer!.videoGravity = AVLayerVideoGravity.resizeAspectFill
previewLayer!.frame = self.bounds
self.layer.addSublayer(previewLayer!)
self.videoPreviewLayer = previewLayer;
}
func removePreviewLayer() {
if self.videoPreviewLayer != nil {
self.videoPreviewLayer!.removeFromSuperlayer()
self.videoPreviewLayer = nil
}
}
}
var cameraView: CameraView!
var captureSession:AVCaptureSession?
var captureVideoPreviewLayer:AVCaptureVideoPreviewLayer?
var metaOutput: AVCaptureMetadataOutput?
var currentCamera: Int = 0;
var frontCamera: AVCaptureDevice?
var backCamera: AVCaptureDevice?
var scanning: Bool = false
var paused: Bool = false
var nextScanningCommand: CDVInvokedUrlCommand?
enum QRScannerError: Int32 {
case unexpected_error = 0,
camera_access_denied = 1,
camera_access_restricted = 2,
back_camera_unavailable = 3,
front_camera_unavailable = 4,
camera_unavailable = 5,
scan_canceled = 6,
light_unavailable = 7,
open_settings_unavailable = 8
}
enum CaptureError: Error {
case backCameraUnavailable
case frontCameraUnavailable
case couldNotCaptureInput(error: NSError)
}
enum LightError: Error {
case torchUnavailable
}
override func pluginInitialize() {
super.pluginInitialize()
NotificationCenter.default.addObserver(self, selector: #selector(pageDidLoad), name: NSNotification.Name.CDVPageDidLoad, object: nil)
self.cameraView = CameraView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
self.cameraView.autoresizingMask = [.flexibleWidth, .flexibleHeight];
}
func sendErrorCode(command: CDVInvokedUrlCommand, error: QRScannerError){
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error.rawValue)
commandDelegate!.send(pluginResult, callbackId:command.callbackId)
}
// utility method
@objc func backgroundThread(delay: Double = 0.0, background: (() -> Void)? = nil, completion: (() -> Void)? = nil) {
if #available(iOS 8.0, *) {
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
if (background != nil) {
background!()
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay * Double(NSEC_PER_SEC)) {
if(completion != nil){
completion!()
}
}
}
} else {
// Fallback for iOS < 8.0
if(background != nil){
background!()
}
if(completion != nil){
completion!()
}
}
}
@objc func prepScanner(command: CDVInvokedUrlCommand) -> Bool{
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if (status == AVAuthorizationStatus.restricted) {
self.sendErrorCode(command: command, error: QRScannerError.camera_access_restricted)
return false
} else if status == AVAuthorizationStatus.denied {
self.sendErrorCode(command: command, error: QRScannerError.camera_access_denied)
return false
}
do {
if (captureSession?.isRunning != true){
cameraView.backgroundColor = UIColor.clear
self.webView!.superview!.insertSubview(cameraView, belowSubview: self.webView!)
let availableVideoDevices = AVCaptureDevice.devices(for: AVMediaType.video)
for device in availableVideoDevices {
if device.position == AVCaptureDevice.Position.back {
backCamera = device
}
else if device.position == AVCaptureDevice.Position.front {
frontCamera = device
}
}
// older iPods have no back camera
if(backCamera == nil){
currentCamera = 1
}
let input: AVCaptureDeviceInput
input = try self.createCaptureDeviceInput()
captureSession = AVCaptureSession()
captureSession!.addInput(input)
metaOutput = AVCaptureMetadataOutput()
captureSession!.addOutput(metaOutput!)
metaOutput!.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
metaOutput!.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
captureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
cameraView.addPreviewLayer(captureVideoPreviewLayer)
captureSession!.startRunning()
}
return true
} catch CaptureError.backCameraUnavailable {
self.sendErrorCode(command: command, error: QRScannerError.back_camera_unavailable)
} catch CaptureError.frontCameraUnavailable {
self.sendErrorCode(command: command, error: QRScannerError.front_camera_unavailable)
} catch CaptureError.couldNotCaptureInput(let error){
print(error.localizedDescription)
self.sendErrorCode(command: command, error: QRScannerError.camera_unavailable)
} catch {
self.sendErrorCode(command: command, error: QRScannerError.unexpected_error)
}
return false
}
@objc func createCaptureDeviceInput() throws -> AVCaptureDeviceInput {
var captureDevice: AVCaptureDevice
if(currentCamera == 0){
if(backCamera != nil){
captureDevice = backCamera!
} else {
throw CaptureError.backCameraUnavailable
}
} else {
if(frontCamera != nil){
captureDevice = frontCamera!
} else {
throw CaptureError.frontCameraUnavailable
}
}
let captureDeviceInput: AVCaptureDeviceInput
do {
captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
} catch let error as NSError {
throw CaptureError.couldNotCaptureInput(error: error)
}
return captureDeviceInput
}
@objc func makeOpaque(){
self.webView?.isOpaque = false
self.webView?.backgroundColor = UIColor.clear
}
@objc func boolToNumberString(bool: Bool) -> String{
if(bool) {
return "1"
} else {
return "0"
}
}
@objc func configureLight(command: CDVInvokedUrlCommand, state: Bool){
var useMode = AVCaptureDevice.TorchMode.on
if(state == false){
useMode = AVCaptureDevice.TorchMode.off
}
do {
// torch is only available for back camera
if(backCamera == nil || backCamera!.hasTorch == false || backCamera!.isTorchAvailable == false || backCamera!.isTorchModeSupported(useMode) == false){
throw LightError.torchUnavailable
}
try backCamera!.lockForConfiguration()
backCamera!.torchMode = useMode
backCamera!.unlockForConfiguration()
self.getStatus(command)
} catch LightError.torchUnavailable {
self.sendErrorCode(command: command, error: QRScannerError.light_unavailable)
} catch let error as NSError {
print(error.localizedDescription)
self.sendErrorCode(command: command, error: QRScannerError.unexpected_error)
}
}
// This method processes metadataObjects captured by iOS.
func metadataOutput(_ captureOutput: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
if metadataObjects.count == 0 || scanning == false {
// while nothing is detected, or if scanning is false, do nothing.
return
}
let found = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
if found.type == AVMetadataObject.ObjectType.qr && found.stringValue != nil {
scanning = false
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: found.stringValue)
commandDelegate!.send(pluginResult, callbackId: nextScanningCommand?.callbackId!)
nextScanningCommand = nil
}
}
@objc func pageDidLoad() {
self.webView?.isOpaque = false
self.webView?.backgroundColor = UIColor.clear
}
// ---- BEGIN EXTERNAL API ----
@objc func prepare(_ command: CDVInvokedUrlCommand){
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if (status == AVAuthorizationStatus.notDetermined) {
// Request permission before preparing scanner
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted) -> Void in
// attempt to prepScanner only after the request returns
self.backgroundThread(delay: 0, completion: {
if(self.prepScanner(command: command)){
self.getStatus(command)
}
})
})
} else {
if(self.prepScanner(command: command)){
self.getStatus(command)
}
}
}
@objc func scan(_ command: CDVInvokedUrlCommand){
if(self.prepScanner(command: command)){
nextScanningCommand = command
scanning = true
}
}
@objc func cancelScan(_ command: CDVInvokedUrlCommand){
if(self.prepScanner(command: command)){
scanning = false
if(nextScanningCommand != nil){
self.sendErrorCode(command: nextScanningCommand!, error: QRScannerError.scan_canceled)
}
self.getStatus(command)
}
}
@objc func show(_ command: CDVInvokedUrlCommand) {
self.webView?.isOpaque = false
self.webView?.backgroundColor = UIColor.clear
self.getStatus(command)
}
@objc func hide(_ command: CDVInvokedUrlCommand) {
self.makeOpaque()
self.getStatus(command)
}
@objc func pausePreview(_ command: CDVInvokedUrlCommand) {
if(scanning){
paused = true;
scanning = false;
}
captureVideoPreviewLayer?.connection?.isEnabled = false
self.getStatus(command)
}
@objc func resumePreview(_ command: CDVInvokedUrlCommand) {
if(paused){
paused = false;
scanning = true;
}
captureVideoPreviewLayer?.connection?.isEnabled = true
self.getStatus(command)
}
// backCamera is 0, frontCamera is 1
@objc func useCamera(_ command: CDVInvokedUrlCommand){
let index = command.arguments[0] as! Int
if(currentCamera != index){
// camera change only available if both backCamera and frontCamera exist
if(backCamera != nil && frontCamera != nil){
// switch camera
currentCamera = index
if(self.prepScanner(command: command)){
do {
captureSession!.beginConfiguration()
let currentInput = captureSession?.inputs[0] as! AVCaptureDeviceInput
captureSession!.removeInput(currentInput)
let input = try self.createCaptureDeviceInput()
captureSession!.addInput(input)
captureSession!.commitConfiguration()
self.getStatus(command)
} catch CaptureError.backCameraUnavailable {
self.sendErrorCode(command: command, error: QRScannerError.back_camera_unavailable)
} catch CaptureError.frontCameraUnavailable {
self.sendErrorCode(command: command, error: QRScannerError.front_camera_unavailable)
} catch CaptureError.couldNotCaptureInput(let error){
print(error.localizedDescription)
self.sendErrorCode(command: command, error: QRScannerError.camera_unavailable)
} catch {
self.sendErrorCode(command: command, error: QRScannerError.unexpected_error)
}
}
} else {
if(backCamera == nil){
self.sendErrorCode(command: command, error: QRScannerError.back_camera_unavailable)
} else {
self.sendErrorCode(command: command, error: QRScannerError.front_camera_unavailable)
}
}
} else {
// immediately return status if camera is unchanged
self.getStatus(command)
}
}
@objc func enableLight(_ command: CDVInvokedUrlCommand) {
if(self.prepScanner(command: command)){
self.configureLight(command: command, state: true)
}
}
@objc func disableLight(_ command: CDVInvokedUrlCommand) {
if(self.prepScanner(command: command)){
self.configureLight(command: command, state: false)
}
}
@objc func destroy(_ command: CDVInvokedUrlCommand) {
self.makeOpaque()
if(self.captureSession != nil){
backgroundThread(delay: 0, background: {
self.captureSession!.stopRunning()
self.cameraView.removePreviewLayer()
self.captureVideoPreviewLayer = nil
self.metaOutput = nil
self.captureSession = nil
self.currentCamera = 0
self.frontCamera = nil
self.backCamera = nil
}, completion: {
self.getStatus(command)
})
} else {
self.getStatus(command)
}
}
@objc func getStatus(_ command: CDVInvokedUrlCommand){
let authorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video);
var authorized = false
if(authorizationStatus == AVAuthorizationStatus.authorized){
authorized = true
}
var denied = false
if(authorizationStatus == AVAuthorizationStatus.denied){
denied = true
}
var restricted = false
if(authorizationStatus == AVAuthorizationStatus.restricted){
restricted = true
}
var prepared = false
if(captureSession?.isRunning == true){
prepared = true
}
var previewing = false
if(captureVideoPreviewLayer != nil){
previewing = captureVideoPreviewLayer!.connection!.isEnabled
}
var showing = false
if(self.webView!.backgroundColor == UIColor.clear){
showing = true
}
var lightEnabled = false
if(backCamera?.torchMode == AVCaptureDevice.TorchMode.on){
lightEnabled = true
}
var canOpenSettings = false
if #available(iOS 8.0, *) {
canOpenSettings = true
}
var canEnableLight = false
if(backCamera?.hasTorch == true && backCamera?.isTorchAvailable == true && backCamera?.isTorchModeSupported(AVCaptureDevice.TorchMode.on) == true){
canEnableLight = true
}
var canChangeCamera = false;
if(backCamera != nil && frontCamera != nil){
canChangeCamera = true
}
let status = [
"authorized": boolToNumberString(bool: authorized),
"denied": boolToNumberString(bool: denied),
"restricted": boolToNumberString(bool: restricted),
"prepared": boolToNumberString(bool: prepared),
"scanning": boolToNumberString(bool: scanning),
"previewing": boolToNumberString(bool: previewing),
"showing": boolToNumberString(bool: showing),
"lightEnabled": boolToNumberString(bool: lightEnabled),
"canOpenSettings": boolToNumberString(bool: canOpenSettings),
"canEnableLight": boolToNumberString(bool: canEnableLight),
"canChangeCamera": boolToNumberString(bool: canChangeCamera),
"currentCamera": String(currentCamera)
]
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: status)
commandDelegate!.send(pluginResult, callbackId:command.callbackId)
}
@objc func openSettings(_ command: CDVInvokedUrlCommand) {
if #available(iOS 10.0, *) {
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
self.getStatus(command)
})
} else {
self.sendErrorCode(command: command, error: QRScannerError.open_settings_unavailable)
}
} else {
// pre iOS 10.0
if #available(iOS 8.0, *) {
UIApplication.shared.openURL(NSURL(string: UIApplicationOpenSettingsURLString)! as URL)
self.getStatus(command)
} else {
self.sendErrorCode(command: command, error: QRScannerError.open_settings_unavailable)
}
}
}
}