UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to retrieve items with the same date from an ItemEntity in Core Data.

Forums > SwiftUI

So basically im taking a basic To Do app and adding functionality where users can check off items, but also get a calculated productivity for each day, and then display it in a graph. I have the graph set up with mock data. But my problem is how do I get all item s with equal dates so that I can perform the calculation:

( Number of tasks completed on the same day / Total number of tasks created on the same day )

My ItemEntity in Core Data has:

name : String date : Date isChecked: Bool productivity: Double

Ive been researching everything for the past few days. Things from using the BackgroundTask api to perform the calculation at 00:00 every day. Then I thought maybe use UserDefaults to store a reference date and when the user returns to the app, if the elapsed time >= 24 hours then the productivity will be set to 0%, otherwise perform the calculation and store the productivity. Now im thinking im over-complicating it and its as simple as finding a way to fetch items only with the same date and doing the calculation on them.

...help me

1      

You will need to create a compound predicate using combined simple predicates that check the date (using predicate parameter substitution).

Try this approach from StackOverflow - CoreData fetch filtered on today.

1      

If you want to "fetch" the same day then you should do it as above. However a better way is to retrive all then do a filter on the result as every time the date changes then will have re-query coredata.

Then you could add this extension

extension Date {
    func isDay(of date: Date) -> Bool {
        let calendar = Calendar.current
        guard let selfDate = calendar.date(from: calendar.dateComponents([.day, .month, .year], from: self)) else {
            fatalError("Unable to get start date from date")
        }

        guard let inputDate = calendar.date(from: calendar.dateComponents([.day, .month, .year], from: date)) else {
            fatalError("Unable to get start date from date")
        }
        return inputDate == selfDate
    }
}

And then if a user want a different data then it can look at that date Here a example

struct ContentView: View {
    @State private var date1 = Date.now
    @State private var date2 = Date.now

    var body: some View {
        VStack(spacing: 50) {
            DatePicker("Date1", selection: $date1, displayedComponents: .date)

            Image(systemName: date1.isDay(of: date2) ? "checkmark.circle" : "x.circle")
                .imageScale(.large)

            DatePicker("Date2", selection: $date2, displayedComponents: .date)
        }
        .padding()
    }
}

if you just want to check for today then do

Image(systemName: date1.isDay(of: Date.now) ? "checkmark.circle" : "x.circle")

1      

Is there a reason to use this:

extension Date {
    func isDay(of date: Date) -> Bool {
        let calendar = Calendar.current
        guard let selfDate = calendar.date(from: calendar.dateComponents([.day, .month, .year], from: self)) else {
            fatalError("Unable to get start date from date")
        }

        guard let inputDate = calendar.date(from: calendar.dateComponents([.day, .month, .year], from: date)) else {
            fatalError("Unable to get start date from date")
        }
        return inputDate == selfDate
    }
}

over this:

extension Date {
    func isDay(of date: Date) -> Bool {
        Calendar.current.isDate(self, inSameDayAs: date)
    }
}

1      

No. Did not know about isDate( ) that all. i just built it from a project to get the first day od month. Always learning something new. PS. is there something like .isToday() as well?

1      

Yep, Calendar has several similar methods:

func isDateInToday(_ date: Date) -> Bool
func isDateInYesterday(_ date: Date) -> Bool
func isDateInTomorrow(_ date: Date) -> Bool

1      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.