forked from LightSys/iOSEventApp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQRScannerViewController.swift
More file actions
232 lines (199 loc) · 10.4 KB
/
QRScannerViewController.swift
File metadata and controls
232 lines (199 loc) · 10.4 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
//
// QRScannerViewController.swift
// iOSEventApp
//
// Created by Nathaniel Brown on 3/5/18.
// Copyright © 2018 LightSys. All rights reserved.
//
// The majority of this file (whatever enables it to scan QR codes) was downloaded from https://www.hackingwithswift.com/example-code/media/how-to-scan-a-qr-code
import UIKit
import AVFoundation
/**
So the idea is that you go in to the QR scanner when you open the app. Once the
QR code has been scanned, the app will stay on that event, sourcing data
through that hyperlink, until otherwise notified. The ability to change the
QR code being used is in settings. We downloaded the QR code reader.
*/
// TODO: Increase the tezt size of the button text, on the ipad it's small and will not fit apple's standards
class QRScannerViewController: UIViewController,
AVCaptureMetadataOutputObjectsDelegate {
weak var delegate: MenuButton?
let loader = DataController(newPersistentContainer: (UIApplication.shared.delegate as! AppDelegate).persistentContainer)
var activityIndicator: UIActivityIndicatorView!
var captureSession: AVCaptureSession!
var previewLayer: AVCaptureVideoPreviewLayer!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.black
captureSession = AVCaptureSession()
}
func failed() {
let ac = UIAlertController(title: "Scanning not supported", message: "Your device does not support scanning a code from an item. Please use a device with a camera.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
captureSession = nil
}
func setupSession() {
var availableDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera, .builtInTelephotoCamera], mediaType: .video, position: .back).devices
if availableDevices.count == 0 {
availableDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera, .builtInTelephotoCamera], mediaType: .video, position: .front).devices
}
guard availableDevices.count > 0 else {
let alertController = UIAlertController(title: "No cameras available", message: "Please check camera permissions", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
self.performSegue(withIdentifier: "PresentMainContainer", sender: nil)
}
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
return
}
let device = availableDevices.first(where: { $0.deviceType == .builtInWideAngleCamera }) ?? availableDevices.first!
let videoInput: AVCaptureDeviceInput
do {
videoInput = try AVCaptureDeviceInput(device: device)
} catch {
let alertController = UIAlertController(title: "Unable to start video session", message: "Please check camera permissions", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
self.performSegue(withIdentifier: "PresentMainContainer", sender: nil)
}
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
return
}
if (captureSession.canAddInput(videoInput)) {
captureSession.addInput(videoInput)
} else {
failed()
return
}
let metadataOutput = AVCaptureMetadataOutput()
if (captureSession.canAddOutput(metadataOutput)) {
captureSession.addOutput(metadataOutput)
metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
metadataOutput.metadataObjectTypes = [.qr]
} else {
failed()
return
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = view.layer.bounds
previewLayer.videoGravity = .resizeAspectFill
view.layer.addSublayer(previewLayer)
activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
activityIndicator.center = view.center
activityIndicator.hidesWhenStopped = true
view.addSubview(activityIndicator)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if captureSession.inputs.count == 0 {
//setupSession()
}
// If they arrive on the scanner, they have come back from the main container – and need to (re)scan.
if (captureSession.isRunning == false) {
//captureSession.startRunning()
}
}
override func viewDidAppear(_ animated: Bool) {
found(code: "https://lan.lightsys.org/events/get.php?id=2a63d094-5987-11ea-95bd-5254004a588e", completion: { (success) in
if success == true {
self.performSegue(withIdentifier: "PresentMainContainer", sender: nil)
}
else {
self.captureSession.startRunning()
}
})
}
// When the app is backgrounded, the capture session is automatically paused, then resumed when foregrounded.
// Not called when backgrounded. So this is only called when leaving for the main container.
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if (captureSession.isRunning == true) {
// captureSession.stopRunning()
}
}
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
//captureSession.stopRunning()
if let metadataObject = metadataObjects.first {
guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else { return }
guard let stringValue = readableObject.stringValue else { return }
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
found(code: stringValue, completion: { (success) in
if success == true {
self.performSegue(withIdentifier: "PresentMainContainer", sender: nil)
}
else {
self.captureSession.startRunning()
}
})
}
else {
captureSession.startRunning()
}
}
/// If there is a url, load data from it. Notify the user of any errors.
///
/// - Parameters:
/// - code: The string form of the QR code scanned
/// - completion: Performed on the main thread
func found(code: String, completion: @escaping ((_ success: Bool) -> Void)) {
if let url = URL(string: code) {
//activityIndicator.startAnimating()
(UIApplication.shared.delegate as! AppDelegate).persistentContainer.performBackgroundTask { (context) in
// The user won't want notifications from a different event... clear everything except chosen refresh rate
UserDefaults.standard.removeObject(forKey: "defaultRefreshRateMinutes")
UserDefaults.standard.removeObject(forKey: "loadedDataURL")
UserDefaults.standard.removeObject(forKey: "loadedNotificationsURL")
UserDefaults.standard.removeObject(forKey: "notificationsLastUpdatedAt")
UserDefaults.standard.removeObject(forKey: "notificationLoadedInBackground")
UserDefaults.standard.removeObject(forKey: "refreshedDataInBackground")
UserDefaults.standard.removeObject(forKey: "currentEvent")
if var savedURLs = UserDefaults.standard.dictionary(forKey: "savedURLs") {
savedURLs["new"] = code
UserDefaults.standard.set(savedURLs, forKey: "savedURLs")
} else {
UserDefaults.standard.set(["new": code], forKey: "savedURLs")
}
self.loader.deleteAllObjects(onContext: context)
self.loader.loadDataFromURL(url, completion: { (success, errors, _) in
DispatchQueue.main.async {
//self.activityIndicator.stopAnimating()
if success == false {
let alertController = UIAlertController(title: "Failed to load data", message: DataController.messageForErrors(errors), preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: { (_) in
completion(success)
})
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
else if errors?.count ?? 0 > 0 {
let alertController = UIAlertController(title: "Data loaded with some errors", message: DataController.messageForErrors(errors), preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: { (_) in
completion(success)
})
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
else {
completion(success)
}
}
})
}
}
else {
let alertController = UIAlertController(title: "Invalid url", message: "\(code) is not a valid url", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: { (_) in
completion(false)
})
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let mainContainer = segue.destination as? MainContainerViewController {
delegate?.refreshSidebar()
mainContainer.delegate = delegate
}
}
}