123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- 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 result = removeNullValuesFromDictionary(data as! [String : Any])
-
-
- let saveData: NSArray = [result]
- let success = saveData.write(toFile: string.expandingTildeInPath as String, atomically: true)
- if (success == true) {
- KMPrint("成功 -" + (string.expandingTildeInPath as String))
- } else {
- KMPrint("失败 -" + (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)
- }
- }
- }
- extension KMLightMemberCache {
-
- func removeNullValuesFromDictionary(_ dictionary: [String: Any]) -> [String: Any] {
- var result: [String: Any] = [:]
- for (key, value) in dictionary {
- if let subDictionary = value as? [NSDictionary] {
-
- var array: [Any] = []
- for item in subDictionary {
- let cleanedSubDictionary = removeNullValuesFromDictionary(item as! [String : Any])
- array.append(cleanedSubDictionary)
- }
- if !array.isEmpty {
- result[key] = array
- }
- } else if let subDictionary = value as? [String: Any] {
-
- let cleanedSubDictionary = removeNullValuesFromDictionary(subDictionary)
- if !cleanedSubDictionary.isEmpty {
- result[key] = cleanedSubDictionary
- }
- } else if !(value is NSNull) {
-
- result[key] = value
- }
- }
- return result
- }
- }
|