我有一个值,我想每周在后台切换到另一个值,当用户在任何一天启动应用程序时,即使它是一个多星期后。当用户在一周内使用该应用程序时,每一天都会变成一个值,例如变量 b 为 false
但我想每周一次将该变量改回 true,以便在它变为 false 的任何一天。我有一个函数,我尝试将其放入 AppDelegate 的 didFinishLaunchingWithOptions
中,但我不确定如何进行检查,因此它不起作用。这是我的尝试:
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
}
}
有人知道怎么做吗?
最佳答案
首先,您可以通过使用 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
}
注意:
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.
接下来,我将使用 NSUserDefaults
作为您的值:
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(true, forKey: "yourVar")
//Then to read it
defaults.boolForKey("yourVar")
关于ios - 每周切换一个存储的标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37853546/