Data類的一個簡單的擴(kuò)展,用來轉(zhuǎn)換json和讀寫剂买。
let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory,FileManager.SearchPathDomainMask.userDomainMask, true).first
let cachePathUrl = URL(fileURLWithPath: cachePath!)
extension Data {
/// json->Data
init?(json:Any) {
if JSONSerialization.isValidJSONObject(json),let data = try? JSONSerialization.data(withJSONObject: json) {
self.init(data)
}else {
return nil
}
}
/// Data->json
func json() -> Any? {
return try? JSONSerialization.jsonObject(with: self)
}
/// wirte data
func write(toCachefilename:String) -> Bool {
try? FileManager.default.createDirectory(at: cachePathUrl, withIntermediateDirectories: true, attributes: nil)
let url = cachePathUrl.appendingPathComponent(toCachefilename)
do {
try self.write(to: url)
return true
}catch {
return false
}
}
/// read data
init?(cachefileName:String) {
let url = cachePathUrl.appendingPathComponent(cachefileName)
do {
try self.init(contentsOf: url, options: .alwaysMapped)
}catch {
return nil
}
}
}