skyguy skyguy - 1 year ago 105
iOS Question

Swift, iOS- NSUserDefaults for days active? Only increment int when it is the first time they opened app on THAT DAY?

I am trying to store an int in NSUserDefaults for the number of days active. Here is how I've been incrementing my NSUSerdefaults:

extension NSUserDefaults {
class func incrementIntegerForKey(key:String) {
let defaults = standardUserDefaults()
let int = defaults.integerForKey(key)
defaults.setInteger(int+1, forKey:key)

Then I call:


I need to increment the int at this key ONLY if it is (not the first time opening the app ever) but the first time they opened the app THAT DAY. Originally I thought of calling this is
however that could be incremented multiple times in 1 day.

Is there a way to do this?
I thought of setting a boolean in NSUserDefaults but I don't know how to reset this boolean every time its a new day, detecting timezones, etc.

How I can count days active?

Using the extension:


Answer Source

First of all this NSDate extension will make things easier

extension NSDate {
    var isToday: Bool {
        let now = NSCalendar.currentCalendar().components([.Day, .Month, .Year], fromDate: NSDate())
        let this = NSCalendar.currentCalendar().components([.Day, .Month, .Year], fromDate: self)
        return now.year == this.year && now.month == this.month && ==

Now your extension can be written as follow

extension NSUserDefaults {
    class func incrementIntegerForKey(key:String) {
        let lastIncreased = NSUserDefaults.standardUserDefaults().valueForKey("lastCheck_\(key)")
        let alreadyIncreasedToday = lastIncreased?.isToday ?? false

        if !alreadyIncreasedToday {
            let counter = NSUserDefaults.standardUserDefaults().integerForKey(key)
            NSUserDefaults.standardUserDefaults().setInteger(counter + 1, forKey: key)
            NSUserDefaults.standardUserDefaults().setValue(NSDate(), forKey: "lastCheck_\(key)")

Please note that this incrementIntegerForKey is NOT thread safe.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download