-
Notifications
You must be signed in to change notification settings - Fork 56
/
ViewController.swift
327 lines (264 loc) · 12.5 KB
/
ViewController.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
import UIKit
import AVFoundation
import CoreData
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDataSource, UITableViewDelegate, PersonViewCellDelegate{
static let CORE_DATA_NAME = "Model"
static let ENTITIES_NAME = "Person"
static let ATTRIBUTE_NAME = "name"
static let ATTRIBUTE_FACE = "face"
static let ATTRIBUTE_TEMPLATES = "templates"
@IBOutlet weak var warningLbl: UILabel!
@IBOutlet weak var enrollBtnView: UIView!
@IBOutlet weak var identifyBtnView: UIView!
@IBOutlet weak var personView: UITableView!
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: ViewController.CORE_DATA_NAME)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var ret = SDK_LICENSE_KEY_ERROR.rawValue
if let filePath = Bundle.main.path(forResource: "license", ofType: "txt") {
do {
let license = try String(contentsOfFile: filePath, encoding: .utf8)
ret = FaceSDK.setActivation(license)
} catch {
print("Error reading file: \(error)")
}
} else {
print("File not found")
}
if(ret == SDK_SUCCESS.rawValue) {
ret = FaceSDK.initSDK()
}
if(ret != SDK_SUCCESS.rawValue) {
warningLbl.isHidden = false
if(ret == SDK_LICENSE_KEY_ERROR.rawValue) {
warningLbl.text = "License key error!"
} else if(ret == SDK_LICENSE_APPID_ERROR.rawValue) {
warningLbl.text = "App ID error!"
} else if(ret == SDK_LICENSE_EXPIRED.rawValue) {
warningLbl.text = "License key expired!"
} else if(ret == SDK_NO_ACTIVATED.rawValue) {
warningLbl.text = "Activation failed!"
} else if(ret == SDK_INIT_ERROR.rawValue) {
warningLbl.text = "Engine init error!"
}
}
SettingsViewController.setDefaultSettings()
personView.delegate = self
personView.dataSource = self
personView.separatorStyle = .none
personView.reloadData()
}
@IBAction func enroll_touch_down(_ sender: Any) {
UIView.animate(withDuration: 0.5) {
self.enrollBtnView.backgroundColor = UIColor(named: "clr_main_button_bg2") // Change to desired color
}
}
@IBAction func enroll_touch_cancel(_ sender: Any) {
UIView.animate(withDuration: 0.5) {
self.enrollBtnView.backgroundColor = UIColor(named: "clr_main_button_bg1") // Change to desired color
}
}
@IBAction func enroll_clicked(_ sender: Any) {
UIView.animate(withDuration: 0.5) {
self.enrollBtnView.backgroundColor = UIColor(named: "clr_main_button_bg1") // Change to desired color
}
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
present(imagePicker, animated: true, completion: nil)
}
@IBAction func identify_touch_down(_ sender: Any) {
UIView.animate(withDuration: 0.5) {
self.identifyBtnView.backgroundColor = UIColor(named: "clr_main_button_bg2") // Change to desired color
}
}
@IBAction func identify_touch_up(_ sender: Any) {
UIView.animate(withDuration: 0.5) {
self.identifyBtnView.backgroundColor = UIColor(named: "clr_main_button_bg1") // Change to desired color
}
}
@IBAction func identify_clicked(_ sender: Any) {
UIView.animate(withDuration: 0.5) {
self.identifyBtnView.backgroundColor = UIColor(named: "clr_main_button_bg1") // Change to desired color
}
performSegue(withIdentifier: "camera", sender: self)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
dismiss(animated: true, completion: nil)
guard let image = info[.originalImage] as? UIImage else {
return
}
let fixed_image = image.fixOrientation()
let faceBoxes = FaceSDK.faceDetection(fixed_image)
if(faceBoxes.count == 0) {
showToast(message: "No face!")
return
} else if(faceBoxes.count > 1) {
showToast(message: "Multiple faces detected!")
}
for faceBox in (faceBoxes as NSArray as! [FaceBox]) {
let templates = FaceSDK.templateExtraction(fixed_image, faceBox: faceBox)
if(templates.isEmpty) {
continue
}
let faceImage = fixed_image.cropFace(faceBox: faceBox)
let context = self.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: ViewController.ENTITIES_NAME, in: context)!
let user = NSManagedObject(entity: entity, insertInto: context)
let currentDate = Date()
let calendar = Calendar.current
let year = calendar.component(.year, from: currentDate)
let month = calendar.component(.month, from: currentDate)
let dayOfMonth = calendar.component(.day, from: currentDate)
let hour = calendar.component(.hour, from: currentDate)
let minute = calendar.component(.minute, from: currentDate)
let second = calendar.component(.second, from: currentDate)
let name = "User " + String(year) + String(month) + String(dayOfMonth) + String(hour) + String(minute) + String(second)
let face = faceImage!.jpegData(compressionQuality: CGFloat(1.0))
user.setValue(name, forKey: ViewController.ATTRIBUTE_NAME)
user.setValue(templates, forKey: ViewController.ATTRIBUTE_TEMPLATES)
user.setValue(face, forKey: ViewController.ATTRIBUTE_FACE)
do {
try context.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
personView.reloadData()
showToast(message: "Registered user successfully")
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
// UITableViewDataSource methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of cells in the table view
let context = self.persistentContainer.viewContext
let count = try! context.count(for: NSFetchRequest(entityName: ViewController.ENTITIES_NAME))
return count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Get the table view cell for the specified index path
let cell = tableView.dequeueReusableCell(withIdentifier: "PersonCell", for: indexPath) as! PersonViewCell
cell.delegate = self
cell.indexPath = indexPath
let context = self.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: ViewController.ENTITIES_NAME)
do {
let persons = try context.fetch(fetchRequest) as! [NSManagedObject]
var rowCount = 0
for person in persons {
if(rowCount == indexPath.row) {
cell.txtName.text = person.value(forKey: ViewController.ATTRIBUTE_NAME) as? String
cell.faceImage.image = UIImage(data: person.value(forKey: ViewController.ATTRIBUTE_FACE) as! Data)
break
}
rowCount = rowCount + 1
}
} catch {
print("Failed fetching: \(error)")
}
// Customize the cell
return cell
}
// UITableViewDelegate methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Handle cell selection
tableView.deselectRow(at: indexPath, animated: true)
}
func didPersonDelete(_ cell: UITableViewCell) {
let context = self.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: ViewController.ENTITIES_NAME)
let personCell = cell as! PersonViewCell
let message = String(format: "Are you sure you want to remove <%@> user?", personCell.txtName.text)
let alertController = UIAlertController(title: "Warning", message: message, preferredStyle: .alert)
let yesAction = UIAlertAction(title: "Yes", style: .default) { _ in
// Code to execute when "Yes" is tapped
do {
let persons = try context.fetch(fetchRequest) as! [NSManagedObject]
var rowCount = 0
for person in persons {
if(rowCount == personCell.indexPath?.row) {
context.delete(person)
try context.save()
break
}
rowCount = rowCount + 1
}
} catch {
print("Failed fetching: \(error)")
}
self.personView.reloadData()
}
let noAction = UIAlertAction(title: "No", style: .cancel) { _ in
// Code to execute when "No" is tapped
print("User tapped No")
}
alertController.addAction(yesAction)
alertController.addAction(noAction)
if let viewController = UIApplication.shared.keyWindow?.rootViewController {
viewController.present(alertController, animated: true, completion: nil)
}
}
func checkUserExist(name: String) -> Bool {
let context = self.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: ViewController.ENTITIES_NAME)
fetchRequest.predicate = NSPredicate(format: "\(ViewController.ATTRIBUTE_NAME) == %@", name)
do {
let existingUsers = try context.fetch(fetchRequest) as! [NSManagedObject]
if existingUsers.isEmpty {
return false
} else {
print("Name already exists in the database")
return true
}
} catch {
print("Failed fetching: \(error)")
}
return false
}
func didNameChanged(_ cell: UITableViewCell) {
let context = self.persistentContainer.viewContext
guard let personCell = cell as? PersonViewCell else {
return
}
guard let updatedName = personCell.txtName.text else {
return
}
let isExistName = checkUserExist(name: updatedName)
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: ViewController.ENTITIES_NAME)
do {
let persons = try context.fetch(fetchRequest) as! [NSManagedObject]
var rowCount = 0
for person in persons {
if(rowCount == personCell.indexPath?.row) {
if (updatedName == person.value(forKey: ViewController.ATTRIBUTE_NAME) as! String) {
break
}
if !isExistName {
print("Updated user name")
person.setValue(updatedName, forKey: ViewController.ATTRIBUTE_NAME)
try context.save()
} else {
personCell.txtName.text = person.value(forKey: ViewController.ATTRIBUTE_NAME) as! String
showToast(message: "Failed! New name already exists in the user list")
}
break
}
rowCount = rowCount + 1
}
} catch {
print("Failed fetching: \(error)")
}
self.personView.reloadData()
}
}