// // KMLightMemberCache.swift // KMLightMember // // Created by lizhe on 2022/11/25. // enum KMLightMemberCacheType: String { case info = "lightMemberInfoCache.plist" case token = "lightMemberTokenCache.plist" } class KMLightMemberCache: NSObject { let kFilePath: NSString = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.path + "KMLightMemberCache" as NSString //单例 public static let cache = KMLightMemberCache() //存储 func saveData(data: NSDictionary, type: KMLightMemberCacheType = .info) { let string: NSString = (kFilePath as String) + "/" + type.rawValue as NSString if (!FileManager.default.fileExists(atPath: string.deletingLastPathComponent as String)) { try?FileManager.default.createDirectory(atPath: string.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil) } if (!FileManager.default.fileExists(atPath: string as String)) { FileManager.default.createFile(atPath: string as String, contents: nil) } //获取有用的参数 let dic: NSMutableDictionary = [:] for key in data.allKeys { let object = data.object(forKey: key) if ( !(object is NSNull)) { dic.setObject(object as Any, forKey: key as! NSCopying) } } let saveData: NSArray = [dic] let success = saveData.write(toFile: string.expandingTildeInPath as String, atomically: true) if (success == true) { print("成功 -" + (string.expandingTildeInPath as String)) } else { print("失败 -" + (string.expandingTildeInPath as String)) } } //读取 func readData( type: KMLightMemberCacheType = .info) -> NSDictionary { let string: NSString = (kFilePath as String) + "/" + type.rawValue as NSString let data = NSArray.init(contentsOfFile: string.expandingTildeInPath as String) if (data != nil) { return data!.firstObject as! NSDictionary } else { return [:] } } func clean() { if (FileManager.default.fileExists(atPath: kFilePath as String)) { try?FileManager.default.removeItem(atPath: kFilePath as String) } } }