Added persistent trip meter.

Save Trip distance even if application is closed.
This commit is contained in:
justin authored and GitHub committed 2025-05-05 18:44:20 -07:00
1 parent 85d2a39fe2
commit 8a678f23c8
1 file changed
+35 -33
+35 -33
View File
@@ -9,41 +9,39 @@ import SwiftUI
import CoreLocation import CoreLocation
struct ContentView: View { struct ContentView: View {
// Location manager to track speed and position @StateObject private var locationManager = LocationManager() // Manages live GPS data
@StateObject private var locationManager = LocationManager() @State private var isMPH = true // Toggle between MPH and KPH
// Unit toggle (true = MPH, false = KPH)
@State private var isMPH = true
// For tracking total trip distance
@State private var previousLocation: CLLocation? @State private var previousLocation: CLLocation?
@State private var tripDistanceMeters: Double = 0.0 @State private var tripDistanceMeters: Double = 0.0 // Trip distance in meters
@State private var isDarkMode = true // Theme toggle: dark/light
// Dark mode toggle @State private var isMinimalView = false // Toggle minimal UI showing only speed
@State private var isDarkMode = true
// Controls whether only speed is shown (minimal view)
@State private var isMinimalView = false
// Computed speed based on selected unit // Load saved trip distance when the view is initialized (even before body runs)
init() {
if let savedDistance = UserDefaults.standard.object(forKey: "TripDistance") as? Double {
_tripDistanceMeters = State(initialValue: savedDistance)
}
}
// Current speed converted to either MPH or KPH
var currentSpeed: Int { var currentSpeed: Int {
let multiplier = isMPH ? 1.0 : 1.60934 let multiplier = isMPH ? 1.0 : 1.60934
return Int(Double(locationManager.speed) * multiplier) return Int(Double(locationManager.speed) * multiplier)
} }
// Label for speed unit // Display correct unit
var unitLabel: String { var unitLabel: String {
isMPH ? "mph" : "kph" isMPH ? "mph" : "kph"
} }
// Distance label (formatted with appropriate unit) // Display formatted trip distance
var distanceLabel: String { var distanceLabel: String {
let distance = isMPH ? tripDistanceMeters * 0.000621371 : tripDistanceMeters / 1000 let distance = isMPH ? tripDistanceMeters * 0.000621371 : tripDistanceMeters / 1000
let roundedDistance = Int(distance.rounded()) let roundedDistance = Int(distance.rounded())
return "\(roundedDistance) \(isMPH ? "miles" : "km")" return "\(roundedDistance) \(isMPH ? "miles" : "km")"
} }
// Color indicating GPS accuracy // Color based on GPS accuracy
var accuracyColor: Color { var accuracyColor: Color {
switch locationManager.accuracy { switch locationManager.accuracy {
case ..<10: case ..<10:
@@ -55,7 +53,7 @@ struct ContentView: View {
} }
} }
// Text and background colors based on theme // Theme-based color helpers
var foregroundColor: Color { var foregroundColor: Color {
isDarkMode ? .white : .black isDarkMode ? .white : .black
} }
@@ -70,14 +68,12 @@ struct ContentView: View {
var body: some View { var body: some View {
ZStack { ZStack {
// Full-screen background color
backgroundColor.ignoresSafeArea() backgroundColor.ignoresSafeArea()
// Main vertical layout
VStack(spacing: 30) { VStack(spacing: 30) {
Spacer() Spacer()
// Speed display with unit // Speed value and unit
HStack(alignment: .bottom, spacing: 4) { HStack(alignment: .bottom, spacing: 4) {
Text("\(currentSpeed)") Text("\(currentSpeed)")
.font(.system(size: 140, weight: .bold, design: .rounded)) .font(.system(size: 140, weight: .bold, design: .rounded))
@@ -87,26 +83,25 @@ struct ContentView: View {
.font(.title2) .font(.title2)
.foregroundColor(secondaryTextColor) .foregroundColor(secondaryTextColor)
.onTapGesture { .onTapGesture {
isMPH.toggle() // Toggle between mph and kph isMPH.toggle() // Tap to switch between MPH/KPH
} }
} }
// Show trip info and controls only if not in minimal view // Extra details (hidden in minimal mode)
if !isMinimalView { if !isMinimalView {
// Trip distance
Text("Trip: \(distanceLabel)") Text("Trip: \(distanceLabel)")
.font(.title2) .font(.title2)
.foregroundColor(secondaryTextColor) .foregroundColor(secondaryTextColor)
// GPS accuracy
Text(String(format: "GPS Accuracy: ±%.0f meters", locationManager.accuracy)) Text(String(format: "GPS Accuracy: ±%.0f meters", locationManager.accuracy))
.font(.headline) .font(.headline)
.foregroundColor(accuracyColor) .foregroundColor(accuracyColor)
// Reset trip button // Reset trip button clears distance and saved value
Button(action: { Button(action: {
tripDistanceMeters = 0 tripDistanceMeters = 0
previousLocation = nil previousLocation = nil
UserDefaults.standard.set(0.0, forKey: "TripDistance") // Clear persistence
}) { }) {
Text("Reset Trip") Text("Reset Trip")
.font(.headline) .font(.headline)
@@ -122,11 +117,11 @@ struct ContentView: View {
} }
.padding() .padding()
// Overlay controls (bottom corners) // Bottom control buttons
VStack { VStack {
Spacer() Spacer()
HStack { HStack {
// 👁 Eye icon to toggle minimal view (bottom-left) // Toggle minimal/full view
Button(action: { Button(action: {
isMinimalView.toggle() isMinimalView.toggle()
}) { }) {
@@ -138,7 +133,7 @@ struct ContentView: View {
Spacer() Spacer()
// ⚙️ Gear icon to open app settings (bottom-right) // Open device Settings
Button(action: { Button(action: {
if let url = URL(string: UIApplication.openSettingsURLString) { if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url) UIApplication.shared.open(url)
@@ -153,11 +148,14 @@ struct ContentView: View {
.padding([.leading, .trailing, .bottom], 10) .padding([.leading, .trailing, .bottom], 10)
} }
} }
// Tap anywhere to toggle dark/light mode
.onTapGesture { .onTapGesture {
isDarkMode.toggle() // Toggle between light and dark mode isDarkMode.toggle()
} }
// Show alert if permissions or GPS fail
.alert(isPresented: $locationManager.showAlert) { .alert(isPresented: $locationManager.showAlert) {
// Show alert if location services are unavailable
Alert( Alert(
title: Text("Location Services"), title: Text("Location Services"),
message: Text(locationManager.alertMessage), message: Text(locationManager.alertMessage),
@@ -168,12 +166,16 @@ struct ContentView: View {
} }
) )
} }
// Track location updates and calculate distance
// Update trip distance whenever a new location is received
.onReceive(locationManager.$location) { location in .onReceive(locationManager.$location) { location in
if let newLocation = location { if let newLocation = location {
if let oldLocation = previousLocation { if let oldLocation = previousLocation {
let distance = newLocation.distance(from: oldLocation) let distance = newLocation.distance(from: oldLocation)
tripDistanceMeters += distance tripDistanceMeters += distance
// Save updated trip distance
UserDefaults.standard.set(tripDistanceMeters, forKey: "TripDistance")
} }
previousLocation = newLocation previousLocation = newLocation
} }