diff --git a/Shared/AppDelegate.swift b/Shared/AppDelegate.swift index 5b0e2a1..62dccfc 100644 --- a/Shared/AppDelegate.swift +++ b/Shared/AppDelegate.swift @@ -16,9 +16,14 @@ class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { // PersistenceController.shared.clearDB() + PersistenceController.shared.fillInMissingDates() UNUserNotificationCenter.current().delegate = self return true } + + func applicationWillEnterForeground(_ application: UIApplication) { + PersistenceController.shared.fillInMissingDates() + } } extension AppDelegate: UNUserNotificationCenterDelegate { diff --git a/Shared/FeelsApp.swift b/Shared/FeelsApp.swift index d65ebb3..0e1c5d9 100644 --- a/Shared/FeelsApp.swift +++ b/Shared/FeelsApp.swift @@ -36,7 +36,6 @@ struct FeelsApp: App { if phase == .active { UIApplication.shared.applicationIconBadgeNumber = 0 - persistenceController.fillInMissingDates() } } } diff --git a/Shared/Persistence.swift b/Shared/Persistence.swift index bbf8c67..da2c26d 100644 --- a/Shared/Persistence.swift +++ b/Shared/Persistence.swift @@ -35,6 +35,11 @@ class PersistenceController { } public func add(mood: Mood, forDate date: Date) { + if let existingEntry = getEntry(byDate: date) { + viewContext.delete(existingEntry) + try? viewContext.save() + } + let newItem = MoodEntry(context: viewContext) newItem.timestamp = Date() newItem.moodValue = Int16(mood.rawValue) @@ -139,14 +144,26 @@ class PersistenceController { fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: false)] let entries = try! viewContext.fetch(fetchRequest) - if let earliestDate = entries.last?.forDate, - let diffInDays = Calendar.current.dateComponents([.day], from: earliestDate, to: Date()).day, - diffInDays > 1 { - for idx in 1..) + for date in missing { + add(mood: .missing, forDate: date) } } } diff --git a/Shared/Random.swift b/Shared/Random.swift index 2eed27b..ba44317 100644 --- a/Shared/Random.swift +++ b/Shared/Random.swift @@ -57,3 +57,17 @@ extension View { clipShape( RoundedCorner(radius: radius, corners: corners) ) } } + +extension Date { + static func dates(from fromDate: Date, to toDate: Date) -> [Date] { + var dates: [Date] = [] + var date = fromDate + + while date <= toDate { + dates.append(date) + guard let newDate = Calendar.current.date(byAdding: .day, value: 1, to: date) else { break } + date = newDate + } + return dates + } +} diff --git a/Shared/views/ContentView.swift b/Shared/views/ContentView.swift index 530494e..1895a4f 100644 --- a/Shared/views/ContentView.swift +++ b/Shared/views/ContentView.swift @@ -368,6 +368,10 @@ struct ContentView: View { theme.currentTheme.bg .edgesIgnoringSafeArea(.all) ) + .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in + PersistenceController.shared.fillInMissingDates() + viewModel.updateData() + } } }