Search code examples
iosswiftdateuserdefaults

How can I keep track of data moving with dates?


I have a school app that keeps track of your schedule. The app has a multitude of options for inputting the schedule. If the user has a four day schedule, then they will have A-D days. For my app. I’d like to keep track of what the current day is (for instance, whether or not it is an A day vs. a C day). The user will be able to specify what day it is when they set up the app, but then the app should keep track of this change day to day, minus weekends. I’m not sure what the best way to implement this is.


Solution

  • I figured out how to keep track of the moving dates, while also not accounting for weekends and updating the value every time it is checked.

    func getCurrentDay() -> Int {
    
        let lastSetDay = //Get the last value of the set day
        let lastSetDayDate = //Get the last time the day was set
        var numberOfDays: Int! //Calculate number of recurring days, for instance an A, B, C, D day schedule would be 4
    
        var currentDay = lastSetDay
        var currentIteratedDate = lastSetDayDate
    
        while Calendar.current.isDate(currentIteratedDate, inSameDayAs: Date()) == false {
            currentIteratedDate = Calendar.current.date(byAdding: .day, value: 1, to: currentIteratedDate)!
            if !Calendar.current.isDateInWeekend(currentIteratedDate) {
                currentDay += 1
            }
            if currentDay > numberOfDays {
                currentDay = 1
            }
        }
    
        if Calendar.current.isDate(currentIteratedDate, inSameDayAs: Date()) == false {
            //Save new day
            //Save new date
        }
    
        return currentDay
    }