Skip to content

Instantly share code, notes, and snippets.

@LuizPanariello
Created September 15, 2023 15:28
Show Gist options
  • Save LuizPanariello/01e03a0bf8b8689eedf3fb2d00e792b5 to your computer and use it in GitHub Desktop.
Save LuizPanariello/01e03a0bf8b8689eedf3fb2d00e792b5 to your computer and use it in GitHub Desktop.
Expirable UserDefaults for swift
class Localstorage {
static func setRecord(key: String, value: Any, duration: TimeInterval) {
let expirationDate = Date().addingTimeInterval(duration);
let expirationKey = key + "_expirable";
let dict = [
expirationKey: expirationDate,
key: value
]
UserDefaults.standard.set(dict, forKey: key);
}
static func getRecord(key: String) -> Any? {
let expirationKey = key + "_expirable"
guard let expirationObject = UserDefaults.standard.dictionary(forKey: key)
else
{
return nil
}
let expirationDate = expirationObject[expirationKey] as! Date;
if Date() > expirationDate { // checks if is before expiration
UserDefaults.standard.removeObject(forKey: key)
return nil;
} else {
return expirationObject[key]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment