Files
Sportstime/SportsTime/Core/Services/AppDelegate.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

83 lines
2.8 KiB
Swift

//
// AppDelegate.swift
// SportsTime
//
// Handles push notification registration and CloudKit subscription notifications
//
import UIKit
import CloudKit
import UserNotifications
class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
// Register for remote notifications (required for CloudKit subscriptions)
application.registerForRemoteNotifications()
return true
}
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
#if DEBUG
print("📡 [Push] Registered for remote notifications")
#endif
}
func application(
_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error
) {
#if DEBUG
print("📡 [Push] Failed to register: \(error.localizedDescription)")
#endif
}
func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
// Ensure completionHandler fires exactly once, even if sync hangs
var hasCompleted = false
let complete: (UIBackgroundFetchResult) -> Void = { result in
guard !hasCompleted else { return }
hasCompleted = true
completionHandler(result)
}
// Timeout: iOS kills background fetches after ~30s, so fire at 25s as safety net
DispatchQueue.main.asyncAfter(deadline: .now() + 25) {
complete(.failed)
}
guard let notification = CKNotification(fromRemoteNotificationDictionary: userInfo) as? CKQueryNotification,
let subscriptionID = notification.subscriptionID,
CloudKitService.canonicalSubscriptionIDs.contains(subscriptionID),
let recordType = CloudKitService.recordType(forSubscriptionID: subscriptionID) else {
complete(.noData)
return
}
Task { @MainActor in
var changed = false
if notification.queryNotificationReason == .recordDeleted,
let recordID = notification.recordID {
changed = await BackgroundSyncManager.shared.applyDeletionHint(
recordType: recordType,
recordName: recordID.recordName
)
}
let updated = await BackgroundSyncManager.shared.triggerSyncFromPushNotification(subscriptionID: subscriptionID)
complete((changed || updated) ? .newData : .noData)
}
}
}