I want to track when was the last time the user refreshed the api, so I decided to do it like this:
@AppStorage("lastTimeUserRefreshedApi") var lastTimeUserRefreshedApi: Date = Date()
func canUserRefreshAPI() -> Bool {
let readyToBeRefreshed: Date = lastTimeUserRefreshedApi.addingTimeInterval(5) // in seconds
let currentTime: Date = Date()
var canUserRefresh: Bool = false
if(currentTime > readyToBeRefreshed) {
canUserRefresh = true
lastTimeUserRefreshedApi = lastTimeUserRefreshedApi.addingTimeInterval(5)
} else {
canUserRefresh = false
}
return canUserRefresh
}
The problem is that it's always returning true, but why? Also is there a simpler way to do this?
Thanks
EDIT:
This is the extension I'm using to be able to store Date in the @AppStorage:
extension Date: RawRepresentable {
public var rawValue: String {
self.timeIntervalSinceReferenceDate.description
}
public init?(rawValue: String) {
self = Date(timeIntervalSinceReferenceDate: Double(rawValue) ?? 0.0)
}
}
CodePudding user response:
You are making it much harder than it should. Just save the "expiration" date. When you read it just compare if it is past or not.
@AppStorage("expiration")
var expiration: Date = Date(timeIntervalSinceNow: 5)
func canUserRefreshAPI() -> Bool {
let now = Date()
if expiration < now {
expiration = Date(timeIntervalSinceNow: 5)
return true
} else {
return false
}
}