KMLightMemberCache.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // KMLightMemberCache.swift
  3. // KMLightMember
  4. //
  5. // Created by lizhe on 2022/11/25.
  6. //
  7. enum KMLightMemberCacheType: String {
  8. case info = "lightMemberInfoCache.plist"
  9. case token = "lightMemberTokenCache.plist"
  10. }
  11. class KMLightMemberCache: NSObject {
  12. let kFilePath: NSString = NSTemporaryDirectory() + "KMLightMemberCache" as NSString
  13. //单例
  14. public static let cache = KMLightMemberCache()
  15. //存储
  16. func saveData(data: NSDictionary, type: KMLightMemberCacheType = .info) {
  17. let string: NSString = (kFilePath as String) + "/" + type.rawValue as NSString
  18. if (!FileManager.default.fileExists(atPath: string.deletingLastPathComponent as String)) {
  19. try?FileManager.default.createDirectory(atPath: string.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  20. }
  21. if (!FileManager.default.fileExists(atPath: string as String)) {
  22. FileManager.default.createFile(atPath: string as String, contents: nil)
  23. }
  24. //获取有用的参数
  25. let dic: NSMutableDictionary = [:]
  26. for key in data.allKeys {
  27. let object = data.object(forKey: key)
  28. if ( !(object is NSNull)) {
  29. dic.setObject(object as Any, forKey: key as! NSCopying)
  30. }
  31. }
  32. let saveData: NSArray = [dic]
  33. let success = saveData.write(toFile: string.expandingTildeInPath as String, atomically: true)
  34. if (success == true) {
  35. print("成功 -" + (string.expandingTildeInPath as String))
  36. } else {
  37. print("失败 -" + (string.expandingTildeInPath as String))
  38. }
  39. }
  40. //读取
  41. func readData( type: KMLightMemberCacheType = .info) -> NSDictionary {
  42. let string: NSString = (kFilePath as String) + "/" + type.rawValue as NSString
  43. let data = NSArray.init(contentsOfFile: string.expandingTildeInPath as String)
  44. if (data != nil) {
  45. return data!.firstObject as! NSDictionary
  46. } else {
  47. return [:]
  48. }
  49. }
  50. func clean() {
  51. if (FileManager.default.fileExists(atPath: kFilePath as String)) {
  52. try?FileManager.default.removeItem(atPath: kFilePath as String)
  53. }
  54. }
  55. }