GPS Speedometer app for iOS.

Speedometer utilizing GPS.
This commit is contained in:
justin authored and GitHub committed 2025-05-05 09:33:00 -07:00
commit a4b504c00d
17 files changed
+1218

No files matched your search

@@ -0,0 +1,11 @@
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,35 @@
{
"images" : [
{
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "tinted"
}
],
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
+133
View File
@@ -0,0 +1,133 @@
//
// ContentView.swift
// Speedometer
//
// Created by Justin Oros on 5/2/2025.
//
import SwiftUI
import CoreLocation
struct ContentView: View {
@StateObject private var locationManager = LocationManager()
@State private var isMPH = true
@State private var previousLocation: CLLocation?
@State private var tripDistanceMeters: Double = 0.0
var currentSpeed: Int {
let multiplier = isMPH ? 1.0 : 1.60934 // Already in MPH from LocationManager
return Int(Double(locationManager.speed) * multiplier)
}
var unitLabel: String {
isMPH ? "mph" : "kph"
}
var distanceLabel: String {
let distance = isMPH ? tripDistanceMeters * 0.000621371 : tripDistanceMeters / 1000
let roundedDistance = Int(distance.rounded())
return "\(roundedDistance) \(isMPH ? "miles" : "km")"
}
var accuracyColor: Color {
switch locationManager.accuracy {
case ..<10:
return .green
case 10..<30:
return .orange
default:
return .red
}
}
var body: some View {
ZStack {
Color.black.ignoresSafeArea()
VStack(spacing: 30) {
Spacer()
// Center Speed Display with Unit
HStack(alignment: .bottom, spacing: 4) {
Text("\(currentSpeed)")
.font(.system(size: 140, weight: .bold, design: .rounded))
.foregroundColor(.white)
Text(unitLabel)
.font(.title2)
.foregroundColor(.gray)
.onTapGesture {
isMPH.toggle()
}
}
// Trip Distance
Text("Trip: \(distanceLabel)")
.font(.title2)
.foregroundColor(.gray)
// GPS Accuracy Display
Text(String(format: "GPS Accuracy: ±%.0f meters", locationManager.accuracy))
.font(.headline)
.foregroundColor(accuracyColor)
// Reset Button (smaller width)
Button(action: {
tripDistanceMeters = 0
previousLocation = nil
}) {
Text("Reset Trip")
.font(.headline)
.padding(.horizontal, 20)
.padding(.vertical, 10)
.background(Color.gray)
.foregroundColor(.black)
.cornerRadius(12)
}
Spacer()
}
.padding()
// Settings Button (Sprocket icon) at the bottom right with padding
VStack {
Spacer()
HStack {
Spacer()
Button(action: {
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url)
}
}) {
Image(systemName: "gearshape.fill") // Sprocket icon
.font(.title2)
.foregroundColor(.white)
.padding()
}
.padding(.bottom, 10) // Add some bottom padding
}
.padding(.trailing) // Keep the trailing padding for right alignment
}
}
.alert(isPresented: $locationManager.showAlert) {
Alert(
title: Text("Location Services"),
message: Text(locationManager.alertMessage),
dismissButton: .default(Text("Settings")) {
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url)
}
}
)
}
.onReceive(locationManager.$location) { location in
if let newLocation = location {
if let oldLocation = previousLocation {
let distance = newLocation.distance(from: oldLocation)
tripDistanceMeters += distance
}
previousLocation = newLocation
}
}
}
}
+115
View File
@@ -0,0 +1,115 @@
//
// LocationManager.swift
// Speedometer
//
// Created by Justin Oros on 5/2/2025.
//
import Foundation
import CoreLocation
import SwiftUI // Import SwiftUI for Alert
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
private let manager = CLLocationManager()
@Published var speed: Int = 0 // MPH as whole number
@Published var location: CLLocation?
@Published var accuracy: Double = 0.0
@Published var authorizationStatus: CLAuthorizationStatus = .notDetermined
@Published var showAlert = false
@Published var alertMessage = ""
override init() {
super.init()
manager.delegate = self
manager.activityType = .automotiveNavigation
manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
manager.distanceFilter = 1 // Update on movement of 1 meter
print("LocationManager initialized")
requestAuthorization() // Request authorization in init
startUpdatingLocationIfNeeded() // Start updates if already authorized
}
private func requestAuthorization() {
print("Requesting location authorization")
manager.requestAlwaysAuthorization() // Request "Always" permission
}
private func startUpdatingLocationIfNeeded() {
if authorizationStatus == .authorizedAlways || authorizationStatus == .authorizedWhenInUse {
print("Attempting to start location updates")
manager.startUpdatingLocation() // Start receiving location updates
} else if authorizationStatus == .denied || authorizationStatus == .restricted {
print("Location updates not started due to denied/restricted authorization")
DispatchQueue.main.async {
self.showAlert = true
self.alertMessage = "Location services are disabled. Please enable them in Settings."
}
} else {
print("Authorization not yet determined, or other status: \(authorizationStatus)")
}
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
DispatchQueue.main.async {
self.authorizationStatus = status
print("Authorization status changed: \(status)")
self.startUpdatingLocationIfNeeded() // Check and start updates on authorization change
}
switch status {
case .authorizedAlways:
print("Location authorization: Authorized Always")
case .authorizedWhenInUse:
print("Location authorization: Authorized When In Use")
case .denied:
print("Location authorization: Denied")
DispatchQueue.main.async {
self.showAlert = true
self.alertMessage = "Location access was denied. Please enable it in Settings for the app to function correctly."
}
case .restricted:
print("Location authorization: Restricted")
DispatchQueue.main.async {
self.showAlert = true
self.alertMessage = "Location access is restricted. This might be due to parental controls or system settings."
}
case .notDetermined:
print("Location authorization: Not Determined")
// Authorization request will be triggered in init
break
@unknown default:
print("Location authorization: Unknown status")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let latest = locations.last else {
print("No latest location found in didUpdateLocations")
return
}
// Debugging output
print("New location received: \(latest.coordinate.latitude), \(latest.coordinate.longitude)")
print("Speed (m/s): \(latest.speed)")
print("Speed (MPH): \(latest.speed * 2.23694)")
print("Accuracy: \(latest.horizontalAccuracy)")
DispatchQueue.main.async {
// Update speed
let rawSpeed = max(latest.speed, 0) // Avoid negative values
let mph = rawSpeed * 2.23694 // Convert m/s to MPH
self.speed = Int(mph.rounded())
self.location = latest
self.accuracy = latest.horizontalAccuracy
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Location update failed: \(error.localizedDescription)")
DispatchQueue.main.async {
self.showAlert = true
self.alertMessage = "Location update failed: \(error.localizedDescription)"
}
}
}
+552
View File
@@ -0,0 +1,552 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 77;
objects = {
/* Begin PBXContainerItemProxy section */
97A3CA3D2DC90F75001ED670 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 97A3CA272DC90F73001ED670 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 97A3CA2E2DC90F73001ED670;
remoteInfo = Speedo;
};
97A3CA472DC90F75001ED670 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 97A3CA272DC90F73001ED670 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 97A3CA2E2DC90F73001ED670;
remoteInfo = Speedo;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
97A3CA2F2DC90F73001ED670 /* Speedo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Speedo.app; sourceTree = BUILT_PRODUCTS_DIR; };
97A3CA3C2DC90F75001ED670 /* SpeedoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SpeedoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
97A3CA462DC90F75001ED670 /* SpeedoUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SpeedoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
97E3710E2DC91223009146A0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Base; path = Base.lproj/Info.plist; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
97A3CA312DC90F73001ED670 /* Speedo */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = Speedo;
sourceTree = "<group>";
};
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
97A3CA2C2DC90F73001ED670 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
97A3CA392DC90F75001ED670 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
97A3CA432DC90F75001ED670 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
97A3CA262DC90F73001ED670 = {
isa = PBXGroup;
children = (
97A3CA312DC90F73001ED670 /* Speedo */,
97A3CA302DC90F73001ED670 /* Products */,
97E3710F2DC91223009146A0 /* Info.plist */,
);
sourceTree = "<group>";
};
97A3CA302DC90F73001ED670 /* Products */ = {
isa = PBXGroup;
children = (
97A3CA2F2DC90F73001ED670 /* Speedo.app */,
97A3CA3C2DC90F75001ED670 /* SpeedoTests.xctest */,
97A3CA462DC90F75001ED670 /* SpeedoUITests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
97A3CA2E2DC90F73001ED670 /* Speedo */ = {
isa = PBXNativeTarget;
buildConfigurationList = 97A3CA502DC90F75001ED670 /* Build configuration list for PBXNativeTarget "Speedo" */;
buildPhases = (
97A3CA2B2DC90F73001ED670 /* Sources */,
97A3CA2C2DC90F73001ED670 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
fileSystemSynchronizedGroups = (
97A3CA312DC90F73001ED670 /* Speedo */,
);
name = Speedo;
packageProductDependencies = (
);
productName = Speedo;
productReference = 97A3CA2F2DC90F73001ED670 /* Speedo.app */;
productType = "com.apple.product-type.application";
};
97A3CA3B2DC90F75001ED670 /* SpeedoTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 97A3CA532DC90F75001ED670 /* Build configuration list for PBXNativeTarget "SpeedoTests" */;
buildPhases = (
97A3CA382DC90F75001ED670 /* Sources */,
97A3CA392DC90F75001ED670 /* Frameworks */,
97A3CA3A2DC90F75001ED670 /* Resources */,
);
buildRules = (
);
dependencies = (
97A3CA3E2DC90F75001ED670 /* PBXTargetDependency */,
);
name = SpeedoTests;
packageProductDependencies = (
);
productName = SpeedoTests;
productReference = 97A3CA3C2DC90F75001ED670 /* SpeedoTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
97A3CA452DC90F75001ED670 /* SpeedoUITests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 97A3CA562DC90F75001ED670 /* Build configuration list for PBXNativeTarget "SpeedoUITests" */;
buildPhases = (
97A3CA422DC90F75001ED670 /* Sources */,
97A3CA432DC90F75001ED670 /* Frameworks */,
97A3CA442DC90F75001ED670 /* Resources */,
);
buildRules = (
);
dependencies = (
97A3CA482DC90F75001ED670 /* PBXTargetDependency */,
);
name = SpeedoUITests;
packageProductDependencies = (
);
productName = SpeedoUITests;
productReference = 97A3CA462DC90F75001ED670 /* SpeedoUITests.xctest */;
productType = "com.apple.product-type.bundle.ui-testing";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
97A3CA272DC90F73001ED670 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1630;
LastUpgradeCheck = 1630;
TargetAttributes = {
97A3CA2E2DC90F73001ED670 = {
CreatedOnToolsVersion = 16.3;
};
97A3CA3B2DC90F75001ED670 = {
CreatedOnToolsVersion = 16.3;
TestTargetID = 97A3CA2E2DC90F73001ED670;
};
97A3CA452DC90F75001ED670 = {
CreatedOnToolsVersion = 16.3;
TestTargetID = 97A3CA2E2DC90F73001ED670;
};
};
};
buildConfigurationList = 97A3CA2A2DC90F73001ED670 /* Build configuration list for PBXProject "Speedo" */;
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 97A3CA262DC90F73001ED670;
minimizedProjectReferenceProxies = 1;
preferredProjectObjectVersion = 77;
productRefGroup = 97A3CA302DC90F73001ED670 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
97A3CA2E2DC90F73001ED670 /* Speedo */,
97A3CA3B2DC90F75001ED670 /* SpeedoTests */,
97A3CA452DC90F75001ED670 /* SpeedoUITests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
97A3CA3A2DC90F75001ED670 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
97A3CA442DC90F75001ED670 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
97A3CA2B2DC90F73001ED670 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
97A3CA382DC90F75001ED670 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
97A3CA422DC90F75001ED670 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
97A3CA3E2DC90F75001ED670 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 97A3CA2E2DC90F73001ED670 /* Speedo */;
targetProxy = 97A3CA3D2DC90F75001ED670 /* PBXContainerItemProxy */;
};
97A3CA482DC90F75001ED670 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 97A3CA2E2DC90F73001ED670 /* Speedo */;
targetProxy = 97A3CA472DC90F75001ED670 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
97E3710F2DC91223009146A0 /* Info.plist */ = {
isa = PBXVariantGroup;
children = (
97E3710E2DC91223009146A0 /* Base */,
);
name = Info.plist;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
97A3CA4E2DC90F75001ED670 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = 5RZLK3W7ZH;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.4;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
97A3CA4F2DC90F75001ED670 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = 5RZLK3W7ZH;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.4;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
97A3CA512DC90F75001ED670 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 5RZLK3W7ZH;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = Speedo/Info.plist;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.justinoros.Speedo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
97A3CA522DC90F75001ED670 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 5RZLK3W7ZH;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = Speedo/Info.plist;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.justinoros.Speedo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
97A3CA542DC90F75001ED670 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 5RZLK3W7ZH;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.4;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.justinoros.SpeedoTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Speedo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Speedo";
};
name = Debug;
};
97A3CA552DC90F75001ED670 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 5RZLK3W7ZH;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.4;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.justinoros.SpeedoTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Speedo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Speedo";
};
name = Release;
};
97A3CA572DC90F75001ED670 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 5RZLK3W7ZH;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.justinoros.SpeedoUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_TARGET_NAME = Speedo;
};
name = Debug;
};
97A3CA582DC90F75001ED670 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 5RZLK3W7ZH;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.justinoros.SpeedoUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_TARGET_NAME = Speedo;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
97A3CA2A2DC90F73001ED670 /* Build configuration list for PBXProject "Speedo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97A3CA4E2DC90F75001ED670 /* Debug */,
97A3CA4F2DC90F75001ED670 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
97A3CA502DC90F75001ED670 /* Build configuration list for PBXNativeTarget "Speedo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97A3CA512DC90F75001ED670 /* Debug */,
97A3CA522DC90F75001ED670 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
97A3CA532DC90F75001ED670 /* Build configuration list for PBXNativeTarget "SpeedoTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97A3CA542DC90F75001ED670 /* Debug */,
97A3CA552DC90F75001ED670 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
97A3CA562DC90F75001ED670 /* Build configuration list for PBXNativeTarget "SpeedoUITests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97A3CA572DC90F75001ED670 /* Debug */,
97A3CA582DC90F75001ED670 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 97A3CA272DC90F73001ED670 /* Project object */;
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>Speedo.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
</dict>
</dict>
</plist>
@@ -0,0 +1,11 @@
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,35 @@
{
"images" : [
{
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "tinted"
}
],
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
+133
View File
@@ -0,0 +1,133 @@
//
// ContentView.swift
// Speedometer
//
// Created by Justin Oros on 5/2/2025.
//
import SwiftUI
import CoreLocation
struct ContentView: View {
@StateObject private var locationManager = LocationManager()
@State private var isMPH = true
@State private var previousLocation: CLLocation?
@State private var tripDistanceMeters: Double = 0.0
var currentSpeed: Int {
let multiplier = isMPH ? 1.0 : 1.60934 // Already in MPH from LocationManager
return Int(Double(locationManager.speed) * multiplier)
}
var unitLabel: String {
isMPH ? "mph" : "kph"
}
var distanceLabel: String {
let distance = isMPH ? tripDistanceMeters * 0.000621371 : tripDistanceMeters / 1000
let roundedDistance = Int(distance.rounded())
return "\(roundedDistance) \(isMPH ? "miles" : "km")"
}
var accuracyColor: Color {
switch locationManager.accuracy {
case ..<10:
return .green
case 10..<30:
return .orange
default:
return .red
}
}
var body: some View {
ZStack {
Color.black.ignoresSafeArea()
VStack(spacing: 30) {
Spacer()
// Center Speed Display with Unit
HStack(alignment: .bottom, spacing: 4) {
Text("\(currentSpeed)")
.font(.system(size: 140, weight: .bold, design: .rounded))
.foregroundColor(.white)
Text(unitLabel)
.font(.title2)
.foregroundColor(.gray)
.onTapGesture {
isMPH.toggle()
}
}
// Trip Distance
Text("Trip: \(distanceLabel)")
.font(.title2)
.foregroundColor(.gray)
// GPS Accuracy Display
Text(String(format: "GPS Accuracy: ±%.0f meters", locationManager.accuracy))
.font(.headline)
.foregroundColor(accuracyColor)
// Reset Button (smaller width)
Button(action: {
tripDistanceMeters = 0
previousLocation = nil
}) {
Text("Reset Trip")
.font(.headline)
.padding(.horizontal, 20)
.padding(.vertical, 10)
.background(Color.gray)
.foregroundColor(.black)
.cornerRadius(12)
}
Spacer()
}
.padding()
// Settings Button (Sprocket icon) at the bottom right with padding
VStack {
Spacer()
HStack {
Spacer()
Button(action: {
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url)
}
}) {
Image(systemName: "gearshape.fill") // Sprocket icon
.font(.title2)
.foregroundColor(.white)
.padding()
}
.padding(.bottom, 10) // Add some bottom padding
}
.padding(.trailing) // Keep the trailing padding for right alignment
}
}
.alert(isPresented: $locationManager.showAlert) {
Alert(
title: Text("Location Services"),
message: Text(locationManager.alertMessage),
dismissButton: .default(Text("Settings")) {
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url)
}
}
)
}
.onReceive(locationManager.$location) { location in
if let newLocation = location {
if let oldLocation = previousLocation {
let distance = newLocation.distance(from: oldLocation)
tripDistanceMeters += distance
}
previousLocation = newLocation
}
}
}
}
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs your location to calculate speed while you're using it.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Location is used to calculate your current speed in real time.</string>
</dict>
</plist>
+113
View File
@@ -0,0 +1,113 @@
//
// LocationManager.swift
// Speedometer
//
// Created by Justin Oros on 5/2/2025.
//
import Foundation
import CoreLocation
import SwiftUI
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
private let manager = CLLocationManager()
@Published var speed: Int = 0
@Published var location: CLLocation?
@Published var accuracy: Double = 0.0
@Published var authorizationStatus: CLAuthorizationStatus = .notDetermined
@Published var showAlert = false
@Published var alertMessage = ""
override init() {
super.init()
manager.delegate = self
manager.activityType = .automotiveNavigation
manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
manager.distanceFilter = 1
print("LocationManager initialized")
requestAuthorization()
startUpdatingLocationIfNeeded()
}
private func requestAuthorization() {
print("Requesting location authorization")
manager.requestWhenInUseAuthorization()
}
private func startUpdatingLocationIfNeeded() {
if authorizationStatus == .authorizedAlways || authorizationStatus == .authorizedWhenInUse {
print("Attempting to start location updates")
manager.startUpdatingLocation()
} else if authorizationStatus == .denied || authorizationStatus == .restricted {
print("Location updates not started due to denied/restricted authorization")
DispatchQueue.main.async {
self.showAlert = true
self.alertMessage = "Location services are disabled. Please enable them in Settings."
}
} else {
print("Authorization not yet determined: \(authorizationStatus.rawValue)")
}
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
let status = manager.authorizationStatus
DispatchQueue.main.async {
self.authorizationStatus = status
print("Authorization status changed: \(status.rawValue)")
self.startUpdatingLocationIfNeeded()
}
switch status {
case .authorizedAlways:
print("Location authorization: Authorized Always")
case .authorizedWhenInUse:
print("Location authorization: Authorized When In Use")
case .denied:
print("Location authorization: Denied")
DispatchQueue.main.async {
self.showAlert = true
self.alertMessage = "Location access was denied. Please enable it in Settings for the app to function correctly."
}
case .restricted:
print("Location authorization: Restricted")
DispatchQueue.main.async {
self.showAlert = true
self.alertMessage = "Location access is restricted. This might be due to parental controls or system settings."
}
case .notDetermined:
print("Location authorization: Not Determined")
@unknown default:
print("Location authorization: Unknown status")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let latest = locations.last else {
print("No latest location found")
return
}
print("New location: \(latest.coordinate.latitude), \(latest.coordinate.longitude)")
print("Speed (m/s): \(latest.speed)")
print("Speed (MPH): \(latest.speed * 2.23694)")
print("Accuracy: \(latest.horizontalAccuracy)")
DispatchQueue.main.async {
let rawSpeed = max(latest.speed, 0)
let mph = rawSpeed * 2.23694
self.speed = Int(mph.rounded())
self.location = latest
self.accuracy = latest.horizontalAccuracy
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Location update failed: \(error.localizedDescription)")
DispatchQueue.main.async {
self.showAlert = true
self.alertMessage = "Location update failed: \(error.localizedDescription)"
}
}
}
+17
View File
@@ -0,0 +1,17 @@
//
// SpeedometerApp.swift
// Speedometer
//
// Created by Justin Oros on 5/2/2025.
//
import SwiftUI
@main
struct SpeedometerApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
+17
View File
@@ -0,0 +1,17 @@
//
// SpeedometerApp.swift
// Speedometer
//
// Created by Justin Oros on 5/2/2025.
//
import SwiftUI
@main
struct SpeedometerApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}