Created
September 15, 2023 15:28
-
-
Save LuizPanariello/01e03a0bf8b8689eedf3fb2d00e792b5 to your computer and use it in GitHub Desktop.
Expirable UserDefaults for swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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