Swift 保存字典plist到沙盒
2023-07-27 本文已影响0人
麦志超
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
}
}