Advertisement
Guest User

Untitled

a guest
Jul 24th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. import Foundation
  2.  
  3. class CacheObject: NSObject, NSCoding {
  4. var value: Any
  5. var expireDate: Date
  6.  
  7. init(value: Any, expireDate: Date) {
  8. self.value = value
  9. self.expireDate = expireDate
  10. }
  11.  
  12. required init?(coder aDecoder: NSCoder) {
  13. self.value = aDecoder.decodeObject(forKey: "value")!
  14. self.expireDate = aDecoder.decodeObject(forKey: "expiredDate") as! Date
  15. }
  16.  
  17. func encode(with aCoder: NSCoder) {
  18. aCoder.encode(value, forKey: "value")
  19. aCoder.encode(expireDate, forKey: "expiredDate")
  20. }
  21. }
  22.  
  23. class ArchiveCache {
  24. static let shared = ArchiveCache()
  25. private init() {
  26. let documentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
  27. cacheBaseURL = documentDirURL.appendingPathComponent("ArchiveCache")
  28. try! FileManager.default.createDirectory(at: cacheBaseURL, withIntermediateDirectories: true, attributes: nil)
  29. }
  30.  
  31. private var memoryCache:[String: CacheObject] = [:]
  32. private var cacheBaseURL: URL
  33.  
  34. func save(key: String, value: Any, seconds: Int) {
  35. let now = Date()
  36. let expireDate = now.addingTimeInterval(TimeInterval(seconds))
  37.  
  38. // save it to memory cache
  39. let cacheObject = CacheObject(value: value, expireDate: expireDate)
  40. memoryCache[key] = cacheObject
  41.  
  42. // save it to disk
  43. let cacheURL = cacheBaseURL.appendingPathComponent("\(key).plist")
  44. NSKeyedArchiver.archiveRootObject(cacheObject, toFile: cacheURL.path)
  45. }
  46.  
  47. func get(key: String) -> Any? {
  48. let now = Date()
  49.  
  50. // get memory cache
  51. if let memoryObject = memoryCache[key] {
  52. if now.timeIntervalSince(memoryObject.expireDate) > 0 {
  53. return nil
  54. } else {
  55. return memoryObject.value
  56. }
  57. }
  58.  
  59. // get disk cache
  60. let cacheURL = cacheBaseURL.appendingPathComponent("\(key).plist")
  61. if let diskObject = NSKeyedUnarchiver.unarchiveObject(withFile: cacheURL.path) as? CacheObject {
  62. if now.timeIntervalSince(diskObject.expireDate) > 0 {
  63. return nil
  64. } else {
  65. return diskObject.value
  66. }
  67. }
  68.  
  69. // nothing found
  70. return nil
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement