ios - 每周切换一个存储的标志

标签 ios swift cocoa-touch

我有一个值,我想每周在后台切换到另一个值,当用户在任何一天启动应用程序时,即使它是一个多星期后。当用户在一周内使用该应用程序时,每一天都会变成一个值,例如变量 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/

相关文章:

iphone - UIlabel - 将文本属性与另一个 NSString 链接

ios - 使用跟踪。 applicationDidBecomeActive 和/或 didFinishLaunchingWithOptions

ios - 使用 curveEaseOut 动画 UIView 子类

arrays - 获取 JSON 数组内的 UICollectionView 单元格 ID 并将其设为全局

objective-c - #define 在 Swift 中是如何工作的?

ios - 未调用 UIPinchGestureRecognizer

ios - '初始化()' is deprecated: init() will be removed in Swift 3. Use ` 零`

ios - 我应该在 init 方法中还是在 didMove(toView :)?) 中以编程方式设置 SKScene

ios - NSMutableArray 中的多个图像

iphone - 属性与实例变量