Search code examples
swift3readfilefile-handlingswifty-jsonwritefile

How store JSON response and save into JSON file


I am using SwiftyJSON to read the API response.

I want to store the JSON response locally in user device by creating JSON file for offline.

My function which returns create 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)

Solution

  • Then now you simply need to get data from the JSON and then use write(to:) method of Data to store JSON response in 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)
    }
    

    Edit: Now later when you want to read JSON from this file access it this way.

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