Files
Sportstime/SportsTime/Export/Services/PDFAssetPrefetcher.swift
Trey t fbb5ae683e Enhance PDF export with maps, images, and progress UI
- Add MapSnapshotService for route maps and city maps using MKMapSnapshotter
- Add RemoteImageService for team logos and stadium photos with caching
- Add POISearchService for nearby attractions using MKLocalSearch
- Add PDFAssetPrefetcher to orchestrate parallel asset fetching
- Rewrite PDFGenerator with rich page layouts: cover, route overview,
  day-by-day itinerary, city spotlights, and summary pages
- Add export progress overlay in TripDetailView with animated progress ring

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 11:53:03 -06:00

181 lines
6.2 KiB
Swift

//
// PDFAssetPrefetcher.swift
// SportsTime
//
// Orchestrates parallel prefetching of all assets needed for PDF generation.
//
import Foundation
import UIKit
actor PDFAssetPrefetcher {
// MARK: - Types
struct PrefetchedAssets {
let routeMap: UIImage?
let cityMaps: [String: UIImage]
let teamLogos: [UUID: UIImage]
let stadiumPhotos: [UUID: UIImage]
let cityPOIs: [String: [POISearchService.POI]]
var isEmpty: Bool {
routeMap == nil && cityMaps.isEmpty && teamLogos.isEmpty && stadiumPhotos.isEmpty && cityPOIs.isEmpty
}
}
struct PrefetchProgress {
var routeMapComplete: Bool = false
var cityMapsComplete: Bool = false
var logosComplete: Bool = false
var photosComplete: Bool = false
var poisComplete: Bool = false
var percentComplete: Double {
let completedSteps = [routeMapComplete, cityMapsComplete, logosComplete, photosComplete, poisComplete]
.filter { $0 }.count
return Double(completedSteps) / 5.0
}
var currentStep: String {
if !routeMapComplete { return "Generating route map..." }
if !cityMapsComplete { return "Generating city maps..." }
if !logosComplete { return "Downloading team logos..." }
if !photosComplete { return "Downloading stadium photos..." }
if !poisComplete { return "Finding nearby attractions..." }
return "Complete"
}
}
// MARK: - Properties
private let mapService = MapSnapshotService()
private let imageService = RemoteImageService()
private let poiService = POISearchService()
// MARK: - Public Methods
/// Prefetch all assets needed for PDF generation
/// - Parameters:
/// - trip: The trip to generate PDF for
/// - games: Map of game IDs to RichGame objects
/// - progressCallback: Optional callback for progress updates
/// - Returns: All prefetched assets
func prefetchAssets(
for trip: Trip,
games: [UUID: RichGame],
progressCallback: ((PrefetchProgress) async -> Void)? = nil
) async -> PrefetchedAssets {
var progress = PrefetchProgress()
// Collect unique teams and stadiums from games
var teams: [Team] = []
var stadiums: [Stadium] = []
var seenTeamIds: Set<UUID> = []
var seenStadiumIds: Set<UUID> = []
for (_, richGame) in games {
if !seenTeamIds.contains(richGame.homeTeam.id) {
teams.append(richGame.homeTeam)
seenTeamIds.insert(richGame.homeTeam.id)
}
if !seenTeamIds.contains(richGame.awayTeam.id) {
teams.append(richGame.awayTeam)
seenTeamIds.insert(richGame.awayTeam.id)
}
if !seenStadiumIds.contains(richGame.stadium.id) {
stadiums.append(richGame.stadium)
seenStadiumIds.insert(richGame.stadium.id)
}
}
// Run all fetches in parallel
async let routeMapTask = fetchRouteMap(stops: trip.stops)
async let cityMapsTask = fetchCityMaps(stops: trip.stops)
async let logosTask = imageService.fetchTeamLogos(teams: teams)
async let photosTask = imageService.fetchStadiumPhotos(stadiums: stadiums)
async let poisTask = poiService.findPOIsForCities(stops: trip.stops, limit: 5)
// Await each result and update progress
let routeMap = await routeMapTask
progress.routeMapComplete = true
await progressCallback?(progress)
let cityMaps = await cityMapsTask
progress.cityMapsComplete = true
await progressCallback?(progress)
let teamLogos = await logosTask
progress.logosComplete = true
await progressCallback?(progress)
let stadiumPhotos = await photosTask
progress.photosComplete = true
await progressCallback?(progress)
let cityPOIs = await poisTask
progress.poisComplete = true
await progressCallback?(progress)
print("[PDFAssetPrefetcher] Prefetch complete:")
print(" - Route map: \(routeMap != nil ? "OK" : "Failed")")
print(" - City maps: \(cityMaps.count) cities")
print(" - Team logos: \(teamLogos.count) logos")
print(" - Stadium photos: \(stadiumPhotos.count) photos")
print(" - POIs: \(cityPOIs.values.reduce(0) { $0 + $1.count }) total POIs")
return PrefetchedAssets(
routeMap: routeMap,
cityMaps: cityMaps,
teamLogos: teamLogos,
stadiumPhotos: stadiumPhotos,
cityPOIs: cityPOIs
)
}
// MARK: - Private Methods
private func fetchRouteMap(stops: [TripStop]) async -> UIImage? {
do {
// PDF page is 612 wide, minus margins
let mapSize = CGSize(width: 512, height: 350)
return try await mapService.generateRouteMap(stops: stops, size: mapSize)
} catch {
print("[PDFAssetPrefetcher] Route map failed: \(error.localizedDescription)")
return nil
}
}
private func fetchCityMaps(stops: [TripStop]) async -> [String: UIImage] {
var results: [String: UIImage] = [:]
let mapSize = CGSize(width: 250, height: 200)
await withTaskGroup(of: (String, UIImage?).self) { group in
// Deduplicate cities
var seenCities: Set<String> = []
for stop in stops {
guard !seenCities.contains(stop.city) else { continue }
seenCities.insert(stop.city)
group.addTask {
do {
let map = try await self.mapService.generateCityMap(stop: stop, size: mapSize)
return (stop.city, map)
} catch {
print("[PDFAssetPrefetcher] City map for \(stop.city) failed: \(error.localizedDescription)")
return (stop.city, nil)
}
}
}
for await (city, map) in group {
if let map = map {
results[city] = map
}
}
}
return results
}
}