Swift 保存字典plist到沙盒

class OSSKeyValueCacheHelper: NSObject {
    
    static let shared = OSSKeyValueCacheHelper()
    
    private let fileManager = FileManager.default
  
    private let cachePath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first ?? "") + "/OSSKeyValueCacheDictionary.plist"
    
    private lazy var tempUrlCacheDict = Dictionary<String, String>()
    
    override init() {
        super.init()
        if fileManager.fileExists(atPath: cachePath) {
            if let dict = loadDictionary() {
                tempUrlCacheDict = dict
            }
        } else {
            fileManager.createFile(atPath: cachePath, contents: try? PropertyListSerialization.data(fromPropertyList: Dictionary<String, String>(), format: PropertyListSerialization.PropertyListFormat.binary, options: 0))
        }
    }
    
    private func getUrlPath() -> URL {
        if #available(iOS 16.0, *) {
            return URL(filePath: cachePath)
        } else {
            return URL(fileURLWithPath: cachePath)
        }
    }
    
    func clearTempUrlCacheDict() {
        tempUrlCacheDict.removeAll()
        saveDictionary(dict: tempUrlCacheDict)
    }
    
    func getTempUrlCacheDict() -> Dictionary<String, String> {
        return tempUrlCacheDict
    }
    
    func saveDictionary(dict: Dictionary<String, String>) {
        try? NSDictionary(dictionary: dict).write(to: getUrlPath())
    }
    
    func loadDictionary() -> Dictionary<String, String>? {
        if let dict = try? NSDictionary(contentsOf: getUrlPath(), error: ()) as? Dictionary<String, String> {
            return dict
        }
        return nil
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容