-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContentView.swift
190 lines (163 loc) · 6.18 KB
/
ContentView.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
import SwiftUI
import CoreLocation
import AVFoundation
struct ContentView: View {
@State private var showSOSAlert = false
@State private var currentLocation: CLLocationCoordinate2D?
@State private var isRecording = false
@State private var emergencyContacts: [String] = [] // Start with an empty list
@State private var newContactName = ""
@State private var newContactNumber = ""
@State private var recorder: AVAudioRecorder?
@StateObject private var locationManagerDelegate = LocationDelegate()
var body: some View {
VStack {
Text("Emergency SOS App")
.font(.largeTitle)
.padding()
Button(action: {
triggerSOSAlert()
}) {
Text("Send SOS Alert")
.font(.title)
.padding()
.background(Color.red)
.foregroundColor(.white)
.cornerRadius(10)
}
if let location = locationManagerDelegate.currentLocation {
Text("Current Location: \(location.latitude), \(location.longitude)")
} else {
Text("Fetching location...")
.foregroundColor(.gray)
}
Button(action: {
toggleRecording()
}) {
Text(isRecording ? "Stop Recording" : "Start Recording")
.font(.title)
.padding()
.background(isRecording ? Color.green : Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
Divider()
.padding(.vertical)
Text("Emergency Contacts")
.font(.headline)
List(emergencyContacts, id: \.self) { contact in
Text(contact)
}
HStack {
TextField("Name", text: $newContactName)
.textFieldStyle(RoundedBorderTextFieldStyle())
TextField("Number", text: $newContactNumber)
.keyboardType(.numberPad)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
.padding()
Button(action: addEmergencyContact) {
Text("Add Contact")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
Spacer()
}
.onAppear {
locationManagerDelegate.setupLocationManager()
}
.alert(isPresented: $showSOSAlert) {
Alert(title: Text("SOS Alert Sent!"),
message: Text("Your SOS alert has been sent to your contacts."),
dismissButton: .default(Text("OK")))
}
}
private func triggerSOSAlert() {
for contact in emergencyContacts {
sendSMS(to: contact)
}
if let location = locationManagerDelegate.currentLocation {
print("Sending Location: \(location.latitude), \(location.longitude)")
}
triggerPanicAlarm()
showSOSAlert.toggle()
}
private func sendSMS(to contact: String) {
print("Sending SMS to \(contact)...")
}
private func triggerPanicAlarm() {
if let url = Bundle.main.url(forResource: "alarm_sound", withExtension: "mp3") {
var audioPlayer: AVAudioPlayer?
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer?.play()
} catch {
print("Error playing panic alarm sound: \(error.localizedDescription)")
}
}
}
private func toggleRecording() {
if isRecording {
stopRecording()
} else {
startRecording()
}
isRecording.toggle()
}
private func startRecording() {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(.playAndRecord, mode: .default, options: .defaultToSpeaker)
try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
let settings: [String: Any] = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100.0,
AVNumberOfChannelsKey: 2,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent("emergencyRecording.m4a")
recorder = try AVAudioRecorder(url: fileURL, settings: settings)
recorder?.record()
} catch {
print("Error starting audio recording: \(error.localizedDescription)")
}
}
private func stopRecording() {
guard let recorder = recorder else {
print("Error: Audio recorder is not initialized.")
return
}
recorder.stop()
}
private func addEmergencyContact() {
guard !newContactName.isEmpty, !newContactNumber.isEmpty else {
print("Error: Both name and number must be provided.")
return
}
let newContact = "\(newContactName) - \(newContactNumber)"
emergencyContacts.append(newContact)
newContactName = ""
newContactNumber = ""
}
}
class LocationDelegate: NSObject, ObservableObject, CLLocationManagerDelegate {
private var locationManager = CLLocationManager()
@Published var currentLocation: CLLocationCoordinate2D?
func setupLocationManager() {
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let newLocation = locations.first {
DispatchQueue.main.async {
self.currentLocation = newLocation.coordinate
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Failed to get location: \(error.localizedDescription)")
}
}