| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- import Foundation
- /// Persists app state (last playlist, last track, playback position) to UserDefaults.
- struct AppState {
- private static let defaults = UserDefaults.standard
- private static let keyLastPlaylistID = "appState.lastPlaylistID"
- private static let keyLastEntryID = "appState.lastEntryID"
- private static let keyLastTrackFilePath = "appState.lastTrackFilePath"
- private static let keyLastPlaybackTime = "appState.lastPlaybackTime"
- // MARK: - Save
- static func saveLastPlaylist(id: UUID) {
- defaults.set(id.uuidString, forKey: keyLastPlaylistID)
- }
- static func saveLastEntry(id: UUID) {
- defaults.set(id.uuidString, forKey: keyLastEntryID)
- }
- static func saveLastTrack(filePath: String) {
- defaults.set(filePath, forKey: keyLastTrackFilePath)
- }
- static func savePlaybackTime(_ time: TimeInterval) {
- defaults.set(time, forKey: keyLastPlaybackTime)
- }
- /// Save all current playback state at once.
- static func savePlaybackState(
- playlistID: UUID?,
- entryID: UUID?,
- trackFilePath: String?,
- playbackTime: TimeInterval
- ) {
- if let id = playlistID { saveLastPlaylist(id: id) }
- if let id = entryID { saveLastEntry(id: id) }
- if let path = trackFilePath { saveLastTrack(filePath: path) }
- savePlaybackTime(playbackTime)
- }
- // MARK: - Load
- static var lastPlaylistID: UUID? {
- defaults.string(forKey: keyLastPlaylistID).flatMap { UUID(uuidString: $0) }
- }
- static var lastEntryID: UUID? {
- defaults.string(forKey: keyLastEntryID).flatMap { UUID(uuidString: $0) }
- }
- static var lastTrackFilePath: String? {
- defaults.string(forKey: keyLastTrackFilePath)
- }
- static var lastPlaybackTime: TimeInterval {
- defaults.double(forKey: keyLastPlaybackTime)
- }
- }
|