Skip to content

Commit

Permalink
Update date upon entering foreground
Browse files Browse the repository at this point in the history
Closes #35
  • Loading branch information
skjiisa committed Jun 2, 2021
1 parent 1b612a6 commit 934c875
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
23 changes: 18 additions & 5 deletions Tickmate/Tickmate/Controllers/TrackController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,7 @@ class TrackController: NSObject, ObservableObject {
Defaults.relativeDates.rawValue: true
])

if UserDefaults.standard.bool(forKey: Defaults.customDayStart.rawValue) {
date = Date() - UserDefaults.standard.integer(forKey: Defaults.customDayStartMinutes.rawValue).minutes
} else {
date = Date()
}
date = Date() - TrackController.dayOffset
weekday = date.in(region: .current).weekday

weekStartDay = UserDefaults.standard.integer(forKey: Defaults.weekStartDay.rawValue)
Expand Down Expand Up @@ -69,6 +65,10 @@ class TrackController: NSObject, ObservableObject {
}
}

static var dayOffset: DateComponents {
(UserDefaults.standard.bool(forKey: Defaults.customDayStart.rawValue) ? UserDefaults.standard.integer(forKey: Defaults.customDayStartMinutes.rawValue) : 0).minutes
}

//MARK: Date Formatters

private var dateFormatter: DateFormatter = {
Expand Down Expand Up @@ -247,6 +247,19 @@ class TrackController: NSObject, ObservableObject {
DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: work)
}

func checkForNewDay() {
// The new date check was done differently in setCustomDayStart, but this works
// too and I don't know if one ways is necissarily better than the other.
let oldDate = TrackController.iso8601.string(from: date)
let newDate = TrackController.iso8601.string(from: Date() - TrackController.dayOffset)
if oldDate != newDate {
objectWillChange.send()
date = Date() - TrackController.dayOffset
tickControllers.values.forEach { $0.loadTicks() }
print("Updated from \(oldDate) to \(newDate)")
}
}

}

//MARK: Fetched Results Controller Delegate
Expand Down
4 changes: 4 additions & 0 deletions Tickmate/Tickmate/Views/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ struct ContentView: View {
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
trackController.scheduleSave(now: true)
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
print("willEnterForeground")
trackController.checkForNewDay()
}
.onAppear {
groupController.trackController = trackController

Expand Down

0 comments on commit 934c875

Please sign in to comment.