Gugulethu Gugulethu - 10 months ago 30
Swift Question

Running a task once a week or periodically, iOS

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? Thanks.


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