Files
Sportstime/SportsTime/Core/Services/LocationService.swift
Trey t c94e373e33 fix: comprehensive codebase hardening — crashes, silent failures, performance, and security
Fixes ~95 issues from deep audit across 12 categories in 82 files:

- Crash prevention: double-resume in PhotoMetadataExtractor, force unwraps in
  DateRangePicker, array bounds checks in polls/achievements, ProGate hit-test
  bypass, Dictionary(uniqueKeysWithValues:) → uniquingKeysWith in 4 files
- Silent failure elimination: all 34 try? sites replaced with do/try/catch +
  logging (SavedTrip, TripDetailView, CanonicalSyncService, BootstrapService,
  CanonicalModels, CKModels, SportsTimeApp, and more)
- Performance: cached DateFormatters (7 files), O(1) team lookups via
  AppDataProvider, achievement definition dictionary, AnimatedBackground
  consolidated from 19 Tasks to 1, task cancellation in SharePreviewView
- Concurrency: UIKit drawing → MainActor.run, background fetch timeout guard,
  @MainActor on ThemeManager/AppearanceManager, SyncLogger read/write race fix
- Planning engine: game end time in travel feasibility, state-aware city
  normalization, exact city matching, DrivingConstraints parameter propagation
- IAP: unknown subscription states → expired, unverified transaction logging,
  entitlements updated before paywall dismiss, restore visible to all users
- Security: API key to Info.plist lookup, filename sanitization in PDF export,
  honest User-Agent, removed stale "Feels" analytics super properties
- Navigation: consolidated competing navigationDestination, boolean → value-based
- Testing: 8 sleep() → waitForExistence, duplicates extracted, Swift 6 compat
- Service bugs: infinite retry cap, duplicate achievement prevention, TOCTOU vote
  fix, PollVote.odg → voterId rename, deterministic placeholder IDs, parallel
  MKDirections, Sendable-safe POI struct

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 17:03:09 -06:00

233 lines
7.2 KiB
Swift

//
// LocationService.swift
// SportsTime
//
import Foundation
import CoreLocation
import MapKit
// SAFETY: MKPolyline is effectively immutable after creation and safe to pass across
// isolation boundaries in practice. A proper fix would extract coordinates into a
// Sendable value type, but MKPolyline is used widely (RouteInfo, map overlays) making
// that refactor non-trivial. Tracked for future cleanup.
extension MKPolyline: @retroactive @unchecked Sendable {}
actor LocationService {
static let shared = LocationService()
private init() {}
// MARK: - Geocoding
func geocode(_ address: String) async throws -> CLLocationCoordinate2D? {
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = address
request.resultTypes = .address
let search = MKLocalSearch(request: request)
let response = try await search.start()
return response.mapItems.first?.location.coordinate
}
func reverseGeocode(_ coordinate: CLLocationCoordinate2D) async throws -> String? {
let request = MKLocalSearch.Request()
request.region = MKCoordinateRegion(
center: coordinate,
latitudinalMeters: 100,
longitudinalMeters: 100
)
request.resultTypes = .address
let search = MKLocalSearch(request: request)
let response = try await search.start()
guard let item = response.mapItems.first else { return nil }
return formatMapItem(item)
}
func resolveLocation(_ input: LocationInput) async throws -> LocationInput {
if input.isResolved { return input }
let searchText = input.address ?? input.name
guard let coordinate = try await geocode(searchText) else {
throw LocationError.geocodingFailed
}
return LocationInput(
name: input.name,
coordinate: coordinate,
address: input.address
)
}
// MARK: - Location Search
func searchLocations(_ query: String) async throws -> [LocationSearchResult] {
guard !query.trimmingCharacters(in: .whitespaces).isEmpty else {
return []
}
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = query
request.resultTypes = [.address, .pointOfInterest]
let search = MKLocalSearch(request: request)
let response = try await search.start()
return response.mapItems.map { item in
LocationSearchResult(
name: item.name ?? "Unknown",
address: formatMapItem(item),
coordinate: item.location.coordinate
)
}
}
private func formatMapItem(_ item: MKMapItem) -> String {
var components: [String] = []
if let cityContext = item.addressRepresentations?.cityWithContext,
!cityContext.isEmpty {
components.append(cityContext)
}
if let regionName = item.addressRepresentations?.regionName,
regionName != "United States" {
components.append(regionName)
}
if !components.isEmpty {
return components.joined(separator: ", ")
}
if let shortAddress = item.address?.shortAddress, !shortAddress.isEmpty {
return shortAddress
}
if let fullAddress = item.address?.fullAddress, !fullAddress.isEmpty {
return fullAddress
}
return item.name ?? ""
}
// MARK: - Distance Calculations
func calculateDistance(
from: CLLocationCoordinate2D,
to: CLLocationCoordinate2D
) -> CLLocationDistance {
let fromLocation = CLLocation(latitude: from.latitude, longitude: from.longitude)
let toLocation = CLLocation(latitude: to.latitude, longitude: to.longitude)
return fromLocation.distance(from: toLocation)
}
func calculateDrivingRoute(
from: CLLocationCoordinate2D,
to: CLLocationCoordinate2D
) async throws -> RouteInfo {
let request = MKDirections.Request()
let fromLocation = CLLocation(latitude: from.latitude, longitude: from.longitude)
let toLocation = CLLocation(latitude: to.latitude, longitude: to.longitude)
request.source = MKMapItem(location: fromLocation, address: nil)
request.destination = MKMapItem(location: toLocation, address: nil)
request.transportType = .automobile
request.requestsAlternateRoutes = false
let directions = MKDirections(request: request)
let response = try await directions.calculate()
guard let route = response.routes.first else {
throw LocationError.routeNotFound
}
return RouteInfo(
distance: route.distance,
expectedTravelTime: route.expectedTravelTime,
polyline: route.polyline
)
}
func calculateDrivingMatrix(
origins: [CLLocationCoordinate2D],
destinations: [CLLocationCoordinate2D]
) async throws -> [[RouteInfo?]] {
let originCount = origins.count
let destCount = destinations.count
// Pre-fill matrix with nils
var matrix: [[RouteInfo?]] = Array(repeating: Array(repeating: nil, count: destCount), count: originCount)
// Calculate all routes concurrently
try await withThrowingTaskGroup(of: (Int, Int, RouteInfo?).self) { group in
for (i, origin) in origins.enumerated() {
for (j, destination) in destinations.enumerated() {
group.addTask {
do {
let route = try await self.calculateDrivingRoute(from: origin, to: destination)
return (i, j, route)
} catch {
return (i, j, nil)
}
}
}
}
for try await (i, j, route) in group {
matrix[i][j] = route
}
}
return matrix
}
}
// MARK: - Route Info
struct RouteInfo: Sendable {
let distance: CLLocationDistance // meters
let expectedTravelTime: TimeInterval // seconds
let polyline: MKPolyline?
var distanceMiles: Double { distance * 0.000621371 }
var travelTimeHours: Double { expectedTravelTime / 3600.0 }
}
// MARK: - Location Search Result
struct LocationSearchResult: Identifiable, Hashable {
let id = UUID()
let name: String
let address: String
let coordinate: CLLocationCoordinate2D
var displayName: String {
if address.isEmpty || name == address {
return name
}
return "\(name), \(address)"
}
func toLocationInput() -> LocationInput {
LocationInput(
name: name,
coordinate: coordinate,
address: address.isEmpty ? nil : address
)
}
}
// MARK: - Errors
enum LocationError: Error, LocalizedError {
case geocodingFailed
case routeNotFound
case permissionDenied
var errorDescription: String? {
switch self {
case .geocodingFailed: return "Unable to find location"
case .routeNotFound: return "Unable to calculate route"
case .permissionDenied: return "Location permission required"
}
}
}