I'm having an issue and could use some help on a time checking method I have written. The functionality should work as follows: Check the time stored in UserDefaults and if the time is more than 1 hour return true.
I've managed to get it working in some sort of way however when the time get's to 23:00 hour there is no 24. I could write an if else block to catch this but I wondered if there's a more simpler way?
Current functionality is:
private func checkTimer() -> Bool {
let date = Date()
let calender = Calendar.current
var getTime = calender.dateComponents([.hour, .minute], from: date)
let intTime = "\(getTime.hour!)\(getTime.minute!)"
let calcTime = Int(intTime)! + 100 // This is where the time gets added to an int i.e. 1246
print("TIME: Calculated time is \(calcTime)")
let lastTimeAccessed = UserDefaults.standard.object(forKey: "Time") as? Int
if (lastTimeAccessed != nil) {
if lastTimeAccessed! >= calcTime {
print("APP: Time has passed")
UserDefaults.standard.set(intTime, forKey: "Time")
return true
} else {
print("TIME: \(intTime)")
print("APP: Not enough time has passed")
return false
}
} else {
UserDefaults.standard.set(intTime, forKey: "Time")
return false
}
}I could use some help on this.
Thanks
If you’re just using this to the limit the rate at which you generate requests, you don’t need to mess around with calendars at all. You can grab the current time and compare it to the previous time. For example:
self.then = Date()
… time passes …
let now = Date()
if now > (then + 3600) {
self.then = now
… do stuff …
}Date counts in seconds since a reference date in UTC, so it’s unaffected by time zone, locale, and so on. Also, while it’s a bad idea to hard-code values like the number of seconds in a day, in this case the number of seconds in an
hour is always 3600 (modulo leap seconds, which you can reasonably ignore).
The only gotcha here relates to the user changing the clock. If they set the clock forward that’s not a problem (you may run an unnecessary request, but it doesn’t sound like that’s a big deal) but if they set the clock backwards your requests could be disabled for a long time. You can avoid this by:
Registering for the
notificationNSSystemClockDidChangeNotificationIf that fires, setting your
value toself.then
so the next request always runsDate.distantPast
Date.distantPast
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"