Advertisement
Guest User

Untitled

a guest
Jun 15th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. import Foundation
  2.  
  3. enum MVDefaultsKey: String {
  4. case requestToken = "defaultsRequestToken"
  5. }
  6.  
  7. /// The class that has multiple class functions for handling defaults.
  8. /// Also has the helper class functions for handling auth tokens.
  9. class MVDefaults {
  10.  
  11. // MARK: - Functions
  12.  
  13. /// Stores token.
  14. class func store<T: Encodable>(_ object: T, key: MVDefaultsKey) {
  15. let encoder = JSONEncoder()
  16. let encoded = try? encoder.encode(object)
  17. UserDefaults.standard.set(encoded, forKey: key.rawValue)
  18. }
  19.  
  20. /// Removes the stored token
  21. class func removeDefaultsWithKey(_ key: MVDefaultsKey) {
  22. UserDefaults.standard.removeObject(forKey: key.rawValue)
  23. }
  24.  
  25. /// Returns stored token (optional) if any.
  26. class func getObjectWithKey<T: Decodable>(_ key: MVDefaultsKey, type: T.Type) -> T? {
  27. guard let savedData = UserDefaults.standard.data(forKey: key.rawValue) else {
  28. return nil
  29. }
  30.  
  31. let object = try? JSONDecoder().decode(type, from: savedData)
  32.  
  33. return object
  34. }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement