From 116c373099af46a11ac4320aac21f58f3549c027 Mon Sep 17 00:00:00 2001 From: ivar Date: Mon, 23 Mar 2026 16:37:31 +0100 Subject: feat: add AppGroupManager for widget-app data syncing --- Solverv/Utilities/AppGroupManager.swift | 67 +++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Solverv/Utilities/AppGroupManager.swift (limited to 'Solverv/Utilities/AppGroupManager.swift') diff --git a/Solverv/Utilities/AppGroupManager.swift b/Solverv/Utilities/AppGroupManager.swift new file mode 100644 index 0000000..95ff2de --- /dev/null +++ b/Solverv/Utilities/AppGroupManager.swift @@ -0,0 +1,67 @@ +import Foundation + +class AppGroupManager { + static let shared = AppGroupManager() + static let appGroupID = "group.com.ivarlovlie.solverv" + + private lazy var userDefaults: UserDefaults? = { + UserDefaults(suiteName: Self.appGroupID) + }() + + // MARK: - Location Storage + + struct UserLocation: Codable { + let latitude: Double + let longitude: Double + let timestamp: String // ISO 8601 + let isDefaultLocation: Bool + } + + func saveLocation(_ location: UserLocation) { + guard let ud = userDefaults else { return } + if let encoded = try? JSONEncoder().encode(location) { + ud.set(encoded, forKey: "userLocation") + } + } + + func getLocation() -> UserLocation? { + guard let ud = userDefaults, + let data = ud.data(forKey: "userLocation"), + let location = try? JSONDecoder().decode(UserLocation.self, from: data) else { + return nil + } + return location + } + + // MARK: - Sunrise/Sunset Storage + + struct SunTimes: Codable { + let date: String // ISO 8601 date only (YYYY-MM-DD) + let sunrise: String // ISO 8601 datetime + let sunset: String // ISO 8601 datetime + let timestamp: String // ISO 8601 when calculated + } + + func saveSunTimes(_ sunTimes: SunTimes) { + guard let ud = userDefaults else { return } + if let encoded = try? JSONEncoder().encode(sunTimes) { + ud.set(encoded, forKey: "sunTimes") + } + } + + func getSunTimes() -> SunTimes? { + guard let ud = userDefaults, + let data = ud.data(forKey: "sunTimes"), + let sunTimes = try? JSONDecoder().decode(SunTimes.self, from: data) else { + return nil + } + return sunTimes + } + + // MARK: - Helpers + + func clearAllData() { + userDefaults?.removeObject(forKey: "userLocation") + userDefaults?.removeObject(forKey: "sunTimes") + } +} -- cgit v1.3