CNLiveFileManager.swift 5.87 KB
//
//  CNLiveFileManager.swift
//  metaCode
//
//  Created by zx on 2023/12/27.
//

import Foundation

class CNLiveFileManager:NSObject{
    //单例类
    static let shared = CNLiveFileManager()
    // MARK: - 属性
    /// 用户id 切换用户时会把当前用户存储路径指空
    var _userId:String?
    var userId:String?{
        get{
            _userId
        }
        set{
            if _userId == newValue{
                self.useDSFileDir = ""
            }
            _userId = newValue
        }
    }

    // MARK: - 储存路径
    /// 存储路径 ~/Document/DS
    var _dsFileDir:String?
    var dsFileDir:String?{
        get{
            if _dsFileDir == nil{
                let path = String(format: "%@/Documents/metaCode/SearchGoods", NSHomeDirectory())
                let fileManager = FileManager.default
                var isDir : ObjCBool = false
                let exist = fileManager.fileExists(atPath: path, isDirectory: &isDir)
                if !(isDir.boolValue && exist) {
                    do {
                        try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true)
                    } catch {
                        debugPrint("文件目录创建失败")
                        return ""
                    }
                }
                _dsFileDir = path
            }
            return _dsFileDir
        }
    }
    /// 当前用户储存路径
    /// 没userId ~/Document/DS/Common/
    /// 有userId ~/Document/DS/userId_XXX/
    // MARK: - 网络缓存
    private lazy var useDSFileDir: String = {
        let userFileDir = NSString()
        var path: String = ""
        path = "\(dsFileDir!)/userId_\(DSUserInfoManager.shared.dsUserInfo.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
    }()

    var _path:String?
    var path:String?{
        get{
            String(format: "%@/storage.plist", self.useDSFileDir )
        }
    }

    // MARK: - 存储、读取、删除
    /// write file 储存
    /// @param object 存储的对象
    /// @param key 存储对象的key
    func saveData(object:Array<Any>,key:String){
        var dic = NSMutableDictionary(contentsOfFile: self.path!)
        if dic == nil{
            dic = NSMutableDictionary()
        }
        dic?.setObject(object, forKey: key as NSCopying)
        dic?.write(toFile: self.path!, atomically: true)
    }
    
    /// write file 读取
    /// @param key 存储对象的key
    func takeDataKey(key:String) -> Array<Any>?{
        var dic = NSMutableDictionary(contentsOfFile: self.path!)
        if dic == nil{
            return nil
        }
        return dic![key] as? Array<Any>
    }
    /// 获取存储的所有数据
    func takeAllSaveData() -> NSDictionary?{
        var dic = NSMutableDictionary(contentsOfFile: self.path!)
        if dic == nil{
            return nil
        }
        return dic!
    }
    /// 删除存储中所有的key
    func resetAllSaveData(){
        var dic = NSMutableDictionary(contentsOfFile: self.path!)
        if dic != nil{
            dic!.removeAllObjects()
            dic!.write(toFile: self.path!, atomically: true)
        }
    }
    /// 删除存储中对应的key
    /// @param resetKey 删除的key
    func deleteKey(resetKey:String){
        var dic = NSMutableDictionary(contentsOfFile: self.path!)
        if dic != nil{
            dic!.removeObject(forKey: resetKey)
            dic!.write(toFile: self.path!, atomically: true)
        }
    }

    /// 计算储存路径目录下所有文件大小 单位字节b
    func calcDSFileDirCacheSize() -> CGFloat {
        let fileManager = FileManager.default
        var size: UInt64 = 0
        var isDir: ObjCBool = false
      
        do {
            let directoryAttributes = try fileManager.attributesOfItem(atPath: self.dsFileDir!)
            isDir = directoryAttributes[FileAttributeKey.type] as? ObjCBool ?? false
        } catch {
            print("Error getting attributes of directory: \(error)")
        }
      
        if isDir.boolValue {
            let fileList = try? fileManager.contentsOfDirectory(atPath: self.dsFileDir!)
            for filePath in fileList ?? [] {
                do {
                    let fileAttributes = try fileManager.attributesOfItem(atPath: (self.dsFileDir! as NSString).appendingPathComponent(filePath))
                    size += fileAttributes[.size] as? UInt64 ?? 0
                } catch {
                    print("Error getting attributes of file: \(error)")
                }
            }
        } else {
            print("The path is not a directory.")
        }
      
        return CGFloat(size)
    }

    /// 清空储存路径缓存
    /// @param completion 清空完成回调
    func clearDSFileDirCacheCompletion(_ completion: @escaping () -> Void) {
        DispatchQueue.global(qos: .userInitiated).async {
            let fileManager = FileManager.default
            let files = try? fileManager.contentsOfDirectory(atPath: self.dsFileDir!)
            for file in files! {
                let path = (self.dsFileDir! as NSString).appendingPathComponent(file)
                do {
                    if FileManager.default.fileExists(atPath: path) {
                        try FileManager.default.removeItem(atPath: path)
                    }
                } catch {
                    print("Error removing item at path: \(path), error: \(error)")
                }
            }
            DispatchQueue.main.async {
                completion()
            }
        }
    }
}