Gugulethu
Gugulethu

Reputation: 1436

Toggle a stored flag on a weekly basis

I have a value I would like to switch to another once a week either in the background on when the user launches the app on whichever day even if it's more than a week later. As the user uses the app during the week, each day turns a value e.g. variable b to false but every once a week I want to change that variable back to true for any day that it's been turned to false. I have a function I tried putting in the AppDelegate's didFinishLaunchingWithOptions but I am not precisely sure how to do the check and hence it didn't work. This is my attempt:

 func resetOnSunday() {

        let date = NSDate()
        let formatter  = NSDateFormatter()
        let timeFormatter = NSDateFormatter()
        formatter.dateFormat = "EEEE"
        let WeekDay = formatter.stringFromDate(date)

        timeFormatter.dateFormat = "HH:mm a"
        let time = timeFormatter.stringFromDate(date)
        if time >= "00:00 AM" && time <= "00:02 AM" && WeekDay == "Sunday" {

 var b = true

        }

    }

Does anyone know how it can be done?

Upvotes: 1

Views: 370

Answers (1)

Chris
Chris

Reputation: 8020

First of all, you can significantly cut down your code (and make it a lot more reliable) by using NSCalendar.

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
//This will return a NSDate optional which you can check against.
let nextSunday = calendar.nextDateAfterDate(date, matchingUnit: .Weekday, value: 1, options: .MatchNextTime)

if date.timeIntervalSinceDate(nextSunday!) > 0 {
  //Do your stuff here
}

Note that:

Weekday units are the numbers 1 through n, where n is the number of days in the week. For example, in the Gregorian calendar, n is 7 and Sunday is represented by 1.

Next, I would use NSUserDefaults for your value:

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(true, forKey: "yourVar")

//Then to read it
defaults.boolForKey("yourVar")

Upvotes: 3

Related Questions