Reputation: 7375
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:
NSUserDefaults.incrementIntegerForKey("daysActive")
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 viewDidLoad
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:
NSUserDefaults.incrementIntegerForKey("daysActive")
Upvotes: 1
Views: 200
Reputation: 59496
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.day == this.day
}
}
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.
Upvotes: 1