AppState.swift 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import Foundation
  2. /// Persists app state (last playlist, last track, playback position) to UserDefaults.
  3. struct AppState {
  4. private static let defaults = UserDefaults.standard
  5. private static let keyLastPlaylistID = "appState.lastPlaylistID"
  6. private static let keyLastEntryID = "appState.lastEntryID"
  7. private static let keyLastTrackFilePath = "appState.lastTrackFilePath"
  8. private static let keyLastPlaybackTime = "appState.lastPlaybackTime"
  9. // MARK: - Save
  10. static func saveLastPlaylist(id: UUID) {
  11. defaults.set(id.uuidString, forKey: keyLastPlaylistID)
  12. }
  13. static func saveLastEntry(id: UUID) {
  14. defaults.set(id.uuidString, forKey: keyLastEntryID)
  15. }
  16. static func saveLastTrack(filePath: String) {
  17. defaults.set(filePath, forKey: keyLastTrackFilePath)
  18. }
  19. static func savePlaybackTime(_ time: TimeInterval) {
  20. defaults.set(time, forKey: keyLastPlaybackTime)
  21. }
  22. /// Save all current playback state at once.
  23. static func savePlaybackState(
  24. playlistID: UUID?,
  25. entryID: UUID?,
  26. trackFilePath: String?,
  27. playbackTime: TimeInterval
  28. ) {
  29. if let id = playlistID { saveLastPlaylist(id: id) }
  30. if let id = entryID { saveLastEntry(id: id) }
  31. if let path = trackFilePath { saveLastTrack(filePath: path) }
  32. savePlaybackTime(playbackTime)
  33. }
  34. // MARK: - Load
  35. static var lastPlaylistID: UUID? {
  36. defaults.string(forKey: keyLastPlaylistID).flatMap { UUID(uuidString: $0) }
  37. }
  38. static var lastEntryID: UUID? {
  39. defaults.string(forKey: keyLastEntryID).flatMap { UUID(uuidString: $0) }
  40. }
  41. static var lastTrackFilePath: String? {
  42. defaults.string(forKey: keyLastTrackFilePath)
  43. }
  44. static var lastPlaybackTime: TimeInterval {
  45. defaults.double(forKey: keyLastPlaybackTime)
  46. }
  47. }