-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContentView-ViewModel.swift
More file actions
89 lines (78 loc) · 2.91 KB
/
ContentView-ViewModel.swift
File metadata and controls
89 lines (78 loc) · 2.91 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
//
// ContentView-ViewModel.swift
// BucketList
//
// Created by Carlos Eduardo Witte on 05/05/25.
//
import Foundation
import CoreLocation
import LocalAuthentication
import MapKit
extension ContentView {
@Observable
class ViewModel {
private(set) var locations: [Location]
var selectedPlace: Location?
var isUnlocked = false
var showHybridMap: Bool = false
var showAlert: Bool = false
var authenticationError = ""
let savePath = URL.documentsDirectory.appending(path: "SavedPlaces")
init() {
do {
let data = try Data(contentsOf: savePath)
locations = try JSONDecoder().decode([Location].self, from: data)
} catch {
locations = []
}
}
func addLocation(at point: CLLocationCoordinate2D) {
let newLocation = Location(
id: UUID(),
name: "New Location",
description: "",
latitude: point.latitude,
longitude: point.longitude
)
locations.append(newLocation)
save()
}
func update(location: Location) {
guard let selectedPlace else { return }
if let index = locations.firstIndex(of: selectedPlace) {
locations[index] = location
save()
}
}
func save() {
do {
let data = try JSONEncoder().encode(locations)
try data.write(to: savePath, options: [.atomic, .completeFileProtection])
} catch {
print("Unable to save data")
}
}
func authenticate() {
let context = LAContext()
var error: NSError?
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
let reason = "Please authenticate yourself to unlock your places."
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authenticationError in
if success {
self.isUnlocked = true
} else {
// biometric (FaceID) authentication failed
self.authenticationError = error?.localizedDescription ?? "You must authenticate yourself to unlock your places."
self.showAlert.toggle()
print(self.authenticationError)
}
}
} else {
// no biometrics
self.authenticationError = error?.localizedDescription ?? "Biometrics authentication is not available on this device."
self.showAlert.toggle()
print(self.authenticationError)
}
}
}
}