import UIKit import Swift import XCPlayground // we want to schedule a timer to fire on Sunday at 4:00am. // NSTimer takes a fire date. // NSTimer.init(fireDate date: NSDate, interval seconds: NSTimeInterval, target target: AnyObject, selector aSelector: Selector, userInfo userInfo: AnyObject?, repeats repeats: Bool) // // So how do we get the date for the next coming Sunday at 4:00am ? // Date Components of course! // Sunday, 4:00 am let resetDay = 1 let resetHour = 4 let resetMinute = 0 func getDateFor(day: Int, hour: Int, minute: Int) -> NSDate? { // Get the Calendar in use let cal = NSCalendar.currentCalendar() // Get the current day, Hour, Minute let todaysComps = cal.components( NSCalendarUnit.CalendarUnitWeekday | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute , fromDate: NSDate()) todaysComps.weekday todaysComps.hour todaysComps.minute // Get the relative components, // This is where the real magic happens, How much time between now and our reset time // in days hours minutes let resetComps = NSDateComponents() resetComps.day = day - todaysComps.day resetComps.hour = hour - todaysComps.hour resetComps.minute = minute - todaysComps.minute // Taking the above differences, add them to now let date = cal.dateByAddingComponents(resetComps, toDate: NSDate(), options: NSCalendarOptions.MatchNextTime) return date //an NSDate? which is the next sunday at 4:00am, useful for settign our timer with } let timerDate = getDateFor(resetDay, resetHour, resetMinute)