如何存储 JSON 响应并保存到 JSON 文件中

How store JSON response and save into JSON file

我正在使用 SwiftyJSON 阅读 API 回复。

我想通过创建 JSON 离线文件将 JSON 响应本地存储在用户设备中。

我 returns 创建的函数 JSON:

 Alamofire.request(HostURL)
        .responseJSON { response in
            guard response.result.isSuccess else {
                debugPrint("getCourseDataFromCourseId: Error while fetching tags \(String(describing: response.result.error))")
                failure(response.result.error! as NSError)
                return
            }

            guard response.result.error == nil else {
                debugPrint(response.result.error!)
                return
            }

            guard let json = response.result.value else {
                debugPrint("JSON Nil")
                return
            }

            let swiftJson = JSON(json)

那么现在你只需要从 JSON 获取数据,然后使用 Datawrite(to:) 方法将 JSON 响应存储在 DocumentDirectory

if let data = try? json.rawData() {
    let fileUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                  .appendingPathComponent("Sample.json") // Your json file name
    try? data.write(to: fileUrl)
}

编辑: 稍后当您想从此文件中读取 JSON 时,请按此方式访问它。

if let data = try? Data(contentsOf: fileURL) {
    let json = JSON(data: data)
}