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