Files
Reflect/Shared/BGTask.swift
Trey t 31fb2a7fe2 Add weather feature with WeatherKit integration for mood entries
Fetch and display weather data (temp, condition, hi/lo, humidity) when
users log a mood. Weather is stored as JSON on MoodEntryModel and shown
as a card in EntryDetailView. Premium-gated with location permission
prompt. Includes BGTask retry for failed fetches and full analytics.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 00:16:26 -05:00

74 lines
2.1 KiB
Swift

//
// BGTask.swift
// Reflect (iOS)
//
// Created by Trey Tartt on 1/12/22.
//
import Foundation
import BackgroundTasks
class BGTask {
static let updateDBMissingID = "com.88oakapps.reflect.dbUpdateMissing"
static let weatherRetryID = "com.88oakapps.reflect.weatherRetry"
@MainActor
class func runFillInMissingDatesTask(task: BGProcessingTask) {
BGTask.scheduleBackgroundProcessing()
task.expirationHandler = {
task.setTaskCompleted(success: false)
}
DataController.shared.fillInMissingDates()
// Catch up on any side effects from widget/watch votes
MoodLogger.shared.processPendingSideEffects()
task.setTaskCompleted(success: true)
}
@MainActor
class func runWeatherRetryTask(task: BGProcessingTask) {
BGTask.scheduleWeatherRetry()
task.expirationHandler = {
task.setTaskCompleted(success: false)
}
Task {
await WeatherManager.shared.retryPendingWeatherFetches()
task.setTaskCompleted(success: true)
}
}
class func scheduleWeatherRetry() {
let request = BGProcessingTaskRequest(identifier: BGTask.weatherRetryID)
request.requiresNetworkConnectivity = true
request.requiresExternalPower = false
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule weather retry: \(error)")
}
}
class func scheduleBackgroundProcessing() {
let request = BGProcessingTaskRequest(identifier: BGTask.updateDBMissingID)
request.requiresNetworkConnectivity = false
request.requiresExternalPower = false
var runDate = Calendar.current.date(byAdding: .day, value: 1, to: Date())
runDate = Calendar.current.date(bySettingHour: 0, minute: 1, second: 0, of: runDate!)
request.earliestBeginDate = runDate
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule image fetch: \(error)")
}
}
}