This repository has been archived by the owner on Oct 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathScannerViewContoller.swift
229 lines (175 loc) · 8.03 KB
/
ScannerViewContoller.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
//
// ScannerViewContoller.swift
// Nano
//
// Created by Zack Shapiro on 12/8/17.
// Copyright © 2017 Nano Wallet Company. All rights reserved.
//
import AVFoundation
import UIKit
import Cartography
import ReactiveSwift
import Result
class ScannerViewContoller: UIViewController {
weak var label: UILabel?
typealias AVCameraScanningCompletionBlock = (_ qrCode: String) -> Void
var scanningCompletionBlock: AVCameraScanningCompletionBlock?
private var captureSession: AVCaptureSession!
private var previewLayer: AVCaptureVideoPreviewLayer!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
if captureSession?.isRunning == false {
self.startRunning()
}
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: animated)
super.viewWillDisappear(animated)
if captureSession?.isRunning == true {
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
self?.captureSession.stopRunning()
}
}
}
override var prefersStatusBarHidden: Bool { return true }
private func createOverlay(view: UIView, at: CGPoint) {
let background = UIView(frame: view.frame)
background.backgroundColor = UIColor.black.withAlphaComponent(0.60)
view.addSubview(background)
let width = view.bounds.width * 0.70
let innerFrame = CGRect(x: ((view.bounds.width - width) / 2), y: ((view.bounds.height - width) / 2), width: width, height: width)
let cutout = UIBezierPath(roundedRect: innerFrame, cornerRadius: 16)
let path = UIBezierPath(roundedRect: background.frame, cornerRadius: 0)
path.append(cutout)
path.usesEvenOddFillRule = true
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
maskLayer.fillRule = kCAFillRuleEvenOdd
let borderLayer = CAShapeLayer()
borderLayer.path = cutout.cgPath
borderLayer.strokeColor = UIColor.white.cgColor
borderLayer.lineWidth = 10
background.layer.addSublayer(borderLayer)
background.layer.mask = maskLayer
let gestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(dismissCamera))
gestureRecognizer.direction = .down
view.addGestureRecognizer(gestureRecognizer)
let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(pinchToZoom(_:)))
view.addGestureRecognizer(pinchGestureRecognizer)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
checkDeviceAuthorizationStatus()
self.captureSession = AVCaptureSession()
guard
let videoCaptureDevice = AVCaptureDevice.default(for: .video),
let videoInput = try? AVCaptureDeviceInput(device: videoCaptureDevice)
else { return }
let metadataOutput = AVCaptureMetadataOutput()
guard captureSession.canAddInput(videoInput), captureSession.canAddOutput(metadataOutput) else { return showNoCameraAlert() }
captureSession.addInput(videoInput)
captureSession.addOutput(metadataOutput)
metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
metadataOutput.metadataObjectTypes = [.aztec, .qr]
self.previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = view.layer.bounds
previewLayer.videoGravity = .resizeAspectFill
view.layer.addSublayer(previewLayer)
createOverlay(view: view, at: CGPoint(x: 250, y: 250))
let dismiss = UIButton()
dismiss.setImage(UIImage(named: "dismissX"), for: .normal)
dismiss.setTitleColor(.white, for: .normal)
dismiss.setBackgroundColor(color: .clear, forState: .normal)
dismiss.addTarget(self, action: #selector(dismissCamera), for: .touchUpInside)
view.addSubview(dismiss)
constrain(dismiss) {
$0.top == $0.superview!.top + CGFloat(24)
$0.left == $0.superview!.left + CGFloat(24)
}
let label = UILabel()
label.font = Styleguide.Fonts.nunitoRegular.font(ofSize: 20)
label.textColor = .white
label.numberOfLines = 0
label.textAlignment = .center
label.lineBreakMode = .byWordWrapping
view.addSubview(label)
constrain(label) {
$0.centerX == $0.superview!.centerX
$0.top == $0.superview!.top + (isiPhoneSE() ? CGFloat(75) : CGFloat(100))
$0.width == $0.superview!.width * CGFloat(0.8)
}
self.label = label
if captureSession?.isRunning == false {
self.startRunning()
}
}
func startRunning() {
DispatchQueue.global(qos: .userInteractive).async { [weak self] in
self?.captureSession.startRunning()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc func dismissCamera() {
return dismiss(animated: true, completion: nil)
}
@objc func pinchToZoom(_ sender: UIPinchGestureRecognizer) {
guard
let videoCaptureDevice = AVCaptureDevice.default(for: .video),
let videoInput = try? AVCaptureDeviceInput(device: videoCaptureDevice)
else { return }
let device = videoInput.device
if sender.state == .changed {
let maxZoomFactor = device.activeFormat.videoMaxZoomFactor
let pinchVelocityDividerFactor: CGFloat = 5.0
do {
try device.lockForConfiguration()
defer { device.unlockForConfiguration() }
let desiredZoomFactor = device.videoZoomFactor + atan2(sender.velocity, pinchVelocityDividerFactor)
device.videoZoomFactor = max(1.0, min(desiredZoomFactor, maxZoomFactor))
} catch {
print(error)
}
}
}
func showNoCameraAlert() {
let ac = UIAlertController(title: "Uh oh!", message: "It looks like your phone is missing a camera. Scanning isn't supported on phones without cameras.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Okay", style: .default))
present(ac, animated: true)
captureSession = nil
}
func checkDeviceAuthorizationStatus() {
AVCaptureDevice.requestAccess(for: .video) { granted in
if !granted {
let ac = UIAlertController(title: "Uh oh!", message: "Nano Wallet doesn't have permission to use the camera.\n\nPlease turn on camera settings under Nano Wallet preferences.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Take Me to Settings", style: .default) { _ in
UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil)
})
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(ac, animated: true)
}
}
}
func startScanning(complete: AVCameraScanningCompletionBlock?) {
self.scanningCompletionBlock = complete
}
func qrCodeProducer() -> SignalProducer<String, NoError> {
return SignalProducer<String, NoError> { [weak self] observer, disposable in
self?.startScanning { observer.send(value: $0) }
}
.skipRepeats()
.observe(on: UIScheduler())
}
}
extension ScannerViewContoller: AVCaptureMetadataOutputObjectsDelegate {
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
if let qrcode = metadataObjects
.filter({ $0.type == .qr || $0.type == .aztec }).first
.flatMap({ ($0 as? AVMetadataMachineReadableCodeObject)?.stringValue }) {
scanningCompletionBlock?(qrcode)
}
}
}