Sfoglia il codice sorgente

Add logic to handle no birthday in profile (#134)

* Add logic to handle no birthday in profile
mdmathias 3 anni fa
parent
commit
7cb0a45d92

+ 12 - 4
Samples/Swift/DaysUntilBirthday/Shared/Models/Birthday.swift

@@ -18,7 +18,7 @@ import Foundation
 
 /// A model type representing the current user's birthday.
 struct Birthday: Decodable {
-  let integerDate: Birthday.IntegerDate
+  fileprivate let integerDate: Birthday.IntegerDate
 
   /// The birthday as a `Date`.
   var date: Date? {
@@ -30,7 +30,7 @@ struct Birthday: Decodable {
                                year: currentYear.year,
                                month: integerDate.month,
                                day: integerDate.day)
-    guard let d = comps.date else { return nil }
+    guard let d = comps.date, comps.isValidDate else { return nil }
     if d < now {
       var nextYearComponent = DateComponents()
       nextYearComponent.year = 1
@@ -39,12 +39,20 @@ struct Birthday: Decodable {
     } else {
       return d
     }
-}
+  }
 
   init(from decoder: Decoder) throws {
     let container = try decoder.container(keyedBy: CodingKeys.self)
     self.integerDate = try container.decode(IntegerDate.self, forKey: .integerDate)
   }
+
+  init(integerDate: IntegerDate) {
+    self.integerDate = integerDate
+  }
+
+  static var noBirthday: Birthday? {
+    return Birthday(integerDate: IntegerDate(month: .min, day: .min))
+  }
 }
 
 extension Birthday {
@@ -64,7 +72,7 @@ extension Birthday {
 extension Birthday: CustomStringConvertible {
   /// Converts the instances `date` to a `String`.
   var description: String {
-    return date?.description ?? "NA"
+    return date?.description ?? "No birthday"
   }
 }
 

+ 7 - 2
Samples/Swift/DaysUntilBirthday/Shared/ViewModels/BirthdayViewModel.swift

@@ -24,11 +24,15 @@ final class BirthdayViewModel: ObservableObject {
   @Published private(set) var birthday: Birthday?
   /// Computed property calculating the number of days until the current user's birthday.
   var daysUntilBirthday: String {
-    guard let bday = birthday?.date else { return "NA" }
+    guard let bday = birthday?.date else {
+      return NSLocalizedString("No birthday", comment: "User has no birthday")
+    }
     let now = Date()
     let calendar = Calendar.autoupdatingCurrent
     let dayComps = calendar.dateComponents([.day], from: now, to: bday)
-    guard let days = dayComps.day else { return "NA" }
+    guard let days = dayComps.day else {
+      return NSLocalizedString("No birthday", comment: "User has no birthday")
+    }
     return String(days)
   }
   private var cancellable: AnyCancellable?
@@ -42,6 +46,7 @@ final class BirthdayViewModel: ObservableObject {
         case .finished:
           break
         case .failure(let error):
+          self.birthday = Birthday.noBirthday
           print("Error retrieving birthday: \(error)")
         }
       } receiveValue: { birthday in