BirthdayViewModel.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * Copyright 2021 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Combine
  17. import Foundation
  18. /// An observable class representing the current user's `Birthday` and the number of days until that
  19. /// date.
  20. final class BirthdayViewModel: ObservableObject {
  21. /// The `Birthday` of the current user.
  22. /// - note: Changes to this property will be published to observers.
  23. @Published private(set) var birthday: Birthday?
  24. /// Computed property calculating the number of days until the current user's birthday.
  25. var daysUntilBirthday: String {
  26. guard let bday = birthday?.date else {
  27. return NSLocalizedString("No birthday", comment: "User has no birthday")
  28. }
  29. let now = Date()
  30. let calendar = Calendar.autoupdatingCurrent
  31. let dayComps = calendar.dateComponents([.day], from: now, to: bday)
  32. guard let days = dayComps.day else {
  33. return NSLocalizedString("No birthday", comment: "User has no birthday")
  34. }
  35. return String(days)
  36. }
  37. private var cancellable: AnyCancellable?
  38. private let birthdayLoader = BirthdayLoader()
  39. /// Fetches the birthday of the current user.
  40. func fetchBirthday() {
  41. Task { @MainActor in
  42. do {
  43. self.birthday = try await birthdayLoader.loadBirthday()
  44. } catch {
  45. print("Error retrieving birthday: \(error)")
  46. self.birthday = .noBirthday
  47. }
  48. }
  49. }
  50. }