import Foundation /// What the widget shows (#428): the unread count and the episode you were last on. Written by /// the app into the App Group the two share, since the widget has no sign-in and no player of its /// own; it shows what the app last knew. struct Snapshot: Codable, Equatable { var unread: Int? var title: String? var feedTitle: String? var position: Double? var duration: Double? var playing = false static let group = "group.net.sdf1.ipx" private static let key = "ipx.snapshot" static func load(from defaults: UserDefaults? = UserDefaults(suiteName: group)) -> Snapshot { defaults?.data(forKey: key).flatMap { try? JSONDecoder().decode(Snapshot.self, from: $0) } ?? Snapshot() } func save(to defaults: UserDefaults? = UserDefaults(suiteName: group)) { if let data = try? JSONEncoder().encode(self) { defaults?.set(data, forKey: Self.key) } } /// How far through, 0 to 1, when both are known. var progress: Double? { guard let position, let duration, duration > 0 else { return nil } return min(1, max(0, position / duration)) } }