CNLiveSavePointDB.swift 2.38 KB
//
//  CNLiveSavePointDB.swift
//  metaCode
//
//  Created by open on 2023/11/15.
//

import Foundation

let CNLiveSavePointCacheKey = "kCNLiveSavePointCacheKey"
class CNLiveSavePointDB: NSObject {
    
    static let shared = CNLiveSavePointDB.init()
    
    open func save(object: MinePointCheckInModel) {
        var temp_dic = NSMutableDictionary.init(contentsOfFile: userFileDir+"storage.plist")
        if (temp_dic == nil) {
            temp_dic = NSMutableDictionary.init()
        }
        temp_dic?.setObject((object.toJSON() ?? Dictionary()) as Dictionary, forKey: CNLiveSavePointCacheKey as NSCopying)
        temp_dic?.write(toFile: userFileDir+"storage.plist", atomically: true)
    }
    
    open func take() -> MinePointCheckInModel {
        let temp_dic = NSMutableDictionary.init(contentsOfFile: userFileDir+"storage.plist")
        if (temp_dic == nil) {
            return MinePointCheckInModel()
        }
        let resp = temp_dic?.object(forKey: CNLiveSavePointCacheKey)
        let listModel = dictionaryToModel(resp as! [String : Any], MinePointCheckInModel.self,"") as! MinePointCheckInModel
        return listModel
    }
    
    private lazy var userFileDir: String = {
        let userFileDir = NSString()
        var path: String = ""
        path = "\(fileDir)/userId_\(UserInfoManager.shared.userInfo.uid)/"
        let fileManager = FileManager.default
        var isDir: ObjCBool = false
        let exist: Bool = fileManager.fileExists(atPath: path, isDirectory: &isDir)
        if !(isDir.boolValue && exist) {
            do {
                try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true)
            } catch {
                debugPrint("文件目录创建失败")
                return ""
            }
        }
        return path as String
    }()

    private lazy var fileDir: String = {
        let path = "\(NSHomeDirectory())/Documents/metaCode/savePoint"
        let fileManager = FileManager.default
        var isDir: ObjCBool = false
        let exist: Bool = fileManager.fileExists(atPath: path, isDirectory: &isDir)
        if !(isDir.boolValue && exist) {
            do {
                try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true)
            } catch {
                debugPrint("文件目录创建失败")
                return ""
            }
        }
        return path as String
    }()
}