Here I'm using an NSPredicate to get this week's Monday history from Core Data using an NSFetchRequest. I don't know why this isn't working can you please help me? I have the same code for Thursday, only the weekday is different, but for some reason it prints out the dates multiple time here is my code and I also attached the console:
func getDateMonday(){
let currentDate = Date()
let calendar = Calendar.current
let weekOfMonth = calendar.component(.weekOfMonth, from: Date())
let month = calendar.component(.month, from: Date())
let mondayComponentStart = DateComponents(month: month, hour: 0, minute: 0, second: 0, weekday: 2, weekOfMonth: weekOfMonth)
let mondayComponentEnd = DateComponents(month: month, hour: 23, minute: 59, second: 59, weekday: 2, weekOfMonth: weekOfMonth )
let lastMondayStart = Calendar.current.nextDate(after: currentDate,
matching: mondayComponentStart,
matchingPolicy: .nextTime,
repeatedTimePolicy: .first,
direction: .backward) ?? Calendar.current.nextDate(after: currentDate, matching: mondayComponentStart, matchingPolicy: .nextTime, repeatedTimePolicy: .first, direction: .forward)
let lastMondayEnd = Calendar.current.nextDate(after: currentDate,
matching: mondayComponentEnd,
matchingPolicy: .nextTime,
repeatedTimePolicy: .first,
direction: .forward) ?? Calendar.current.nextDate(after: currentDate, matching: mondayComponentEnd, matchingPolicy: .nextTime, repeatedTimePolicy: .first, direction: .backward)
let predicateStart = NSPredicate(format: "date >= %@", lastMondayStart! as NSDate)
let predicateEnd = NSPredicate(format: "date <= %@", lastMondayEnd! as NSDate)
let allPredicate = NSCompoundPredicate(type: .and, subpredicates: [predicateStart, predicateEnd])
let waterFetch = NSFetchRequest<Water>(entityName: "Water")
waterFetch.predicate = allPredicate
do {
print(lastMondayStart!)
print(Date())
print(lastMondayEnd!)
print("------------------")
let waterF = try viewContext.fetch(waterFetch)
for all in waterF {
let tot = all.amount
monday += Int(tot)
Total += Int(tot)
}
} catch {
}
}
Okay so the problem was very stupid, because I mistyped one of the functions and I accidentally called one function twice