美文网首页
本地JSON的读写

本地JSON的读写

作者: 竹菜板 | 来源:发表于2017-03-25 10:09 被阅读12次
import SwiftyJSON

let fileManager = FileManager.default
let jsonPath = NSHomeDirectory() + "/Documents/json_name.json"

func save(json: JSON) -> Bool {
    guard let string = json.rawString() else { return false }
    do {
        try string.write(toFile: jsonPath, atomically: true, encoding: String.Encoding.utf8)
        return true
    } catch {
        return false
    }
}

func get() -> JSON? {
    guard fileManager.fileExists(atPath: jsonPath) else { return nil }
    let url = URL(fileURLWithPath: jsonPath)
    do {
        let data = try Data(contentsOf: url)
        let jsonObject = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
        return JSON(jsonObject)
    } catch {
        return nil
    }
}

相关文章

网友评论

      本文标题:本地JSON的读写

      本文链接:https://www.haomeiwen.com/subject/lezqottx.html