I have created a ToDo app that has a 'Todays Tasks' view showing those tasks that are active today. The view works fine onlt showing today's tasks from a SwiftDate Query and split into priority groups.
The problem that I am facing is when midnight ticks over there will be some extra tasks to add to Today's List that have been hidden by the predicate to this point, but there has been no change in the data, only in the query results. I have incorporated a hack/work around that will refresh the view using Pull to Refresh so the view can be updated every morning by users, but after numerous experiments and hours of googling I can't find a way that updates the view at Midnight.
Anybody encountered this before and have a solution?
View Code is:
struct ContentView: View {
@Environment(\.modelContext) var modelContext
@State private var navPath = [Task]()
@State private var sortOrder = SortDescriptor(\Task.startDate, order: .reverse)
@State private var refreshView = false
var body: some View {
NavigationStack(path: $navPath) {
Form {
Section("Critical Now") {
TaskListView(searchPriority: 1, viewType: "Today")
}
.headerProminence(.increased)
Section("Opportunity Now") {
TaskListView(searchPriority: 2, viewType: "Today")
}
.headerProminence(.increased)
Section("Over The Horizon") {
TaskListView(searchPriority: 3, viewType: "Today")
}
.headerProminence(.increased)
}
.id(refreshView)
.refreshable {
refreshView.toggle()
}
.navigationTitle("Today's Tasks")
.navigationDestination(for: Task.self) { task in
EditTaskView(task: task)
}
.toolbar {
Button(action: addNewTask) {
Label("Add new task", systemImage: "text.badge.plus")
}
}
}
}
And the TaskListView that creates the rows is:
struct TaskListView: View {
@Query var tasks: [Task]
@Environment(\.modelContext) var modelContext
let today = Date().endOfDay()
init(searchPriority: Int, viewType: String) {
_tasks = Query(filter: #Predicate { task in
if viewType == "Today" {
task.priority == searchPriority && task.completed == false && task.startDate <= today
} else if viewType == "AllNow" {
task.priority == searchPriority && task.completed == false
} else {
task.priority == searchPriority && task.completed == true
}
}, sort: \Task.startDate, order: .reverse)
}
var body: some View {
List {
ForEach(tasks) { task in
NavigationLink(value: task) {
VStack(alignment: .leading) {
HStack {
if task.startDate.isToday() {
Text(task.name)
.foregroundColor(.blue)
} else {
Text(task.name)
}
Spacer()
if task.startDate.isToday() {
Text(task.startDate, style: .date)
.foregroundColor(.blue)
} else {
Text(task.startDate, style: .date)
}
}
if !task.details.isEmpty {
Text(task.details)
.foregroundStyle(.secondary)
}
}
.swipeActions(edge: .leading) {
Button {
task.completeTask()
} label: {
Label("Complete", systemImage: "checkmark")
}
.tint(.green)
}
.swipeActions(edge: .trailing) {
Button("Delete", systemImage: "trash", role: .destructive) {
modelContext.delete(task)
}
}
}
}
}
}
}