简体   繁体   中英

Save JSON response as JSON file

I want to save my JSON response to a JSON file in document or any other directory.

Earlier I was trying to save the response in coreData but that was a heavy and slow task.

//API Manager function

func loadEmployees(urlString: String, completion: @escaping ((Any?,Error?) -> ())){

    guard let url = URL(string: urlString) else { return }
    var request = URLRequest(url: url)

    request.httpMethod = RequestMethod.get.rawValue

    let session = URLSession.shared
    let sessionTask = session.dataTask(with: request) { (data, response, error) in

        if error ==  nil {
            let result = try? JSONDecoder().decode([EmployeeDetails].self, from: data!)
            completion(result, nil)
        }
        else {
            completion(nil, ServiceError.customError("Please check your internet connection"))
        }
    }
    sessionTask.resume()
}

//I am calling it in my View Controller

    NetworkManager.sharedInstance.loadEmployees(urlString: EMPLOYEEBASEURL, completion: { (data, responseError) in

        if let error = responseError {
            self.showToast(controller: self, message: error.localizedDescription, seconds: 1.6)
        }else{
            if data != nil {
                DispatchQueue.global().async {
                    self.employeeListArray = data as! [EmployeeDetails]
                    self.filteredEmployeeArray = self.employeeListArray

                    DispatchQueue.main.async {
                        self.loader.isHidden = true
                        self.employeeTableView.reloadData()
                    }
                }
            }
        }
    })

//My model

struct EmployeeDetails: Decodable {
    let id: String?
    let name: String?
    let salary: String?
    let age: String?
    let profileImage: String?

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case name = "employee_name"
        case salary = "employee_salary"
        case age = "employee_age"
        case profileImage = "profile_image"
    }
}

Now Instead of parsing it directly I want to save the response in a json file and parse from the file.

I can install any pods if required, my Project is in Swift 5.0 so newer methods are also acceptable.

To save:-

 func saveJsonFile(_ name:String, data:Data) {
    // Get the url of File in document directory
    guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
    let fileUrl = documentDirectoryUrl.appendingPathComponent(name + ".json")

    // Transform array into data and save it into file
    do {
        //let data = try JSONSerialization.data(withJSONObject: list, options: [])
        try data.write(to: fileUrl, options: .completeFileProtection)
    } catch {
        print(error)
    }
}

Retrive:-

func retrieveFromJsonFile(_ name:String) -> [JSONObject]? {
    // Get the url of File in document directory
    guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil}
    let fileUrl = documentsDirectoryUrl.appendingPathComponent(name + ".json")

    // Check for file in file manager.
    guard  (FileManager.default.fileExists(atPath: fileUrl.path))else {return nil}

    // Read data from .json file and transform data into an array
    do {
        let data = try Data(contentsOf: fileUrl, options: [])
        guard let list = try JSONSerialization.jsonObject(with: data, options: []) as? [JSONObject] else { return nil}
        //print(list)
        return list
    } catch {
        print(error)
        return nil
    }
}

Delete json file:-

func removeFile(with name: String){
    // Path for the file.
    guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return}
    let fileUrl = documentsDirectoryUrl.appendingPathComponent(name + ".json")

    if (FileManager.default.fileExists(atPath: fileUrl.absoluteString)){
        do{
            try FileManager.default.removeItem(at: fileUrl)
        }catch{
            print(error.localizedDescription)
        }
    }
}

where JSONObject:- [String: Any]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM