1
if let path = Bundle.main.path(forResource: "domaines", ofType: "json") {
    if JSONSerialization.isValidJSONObject(dict){
        do{
            let rawData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
            try rawData.write(to: URL(fileURLWithPath: path))
        }catch{
        }
    }else{
    }
}else{
    print("file not present")
}

This is the code used by me but I'm not able to save the data to the local JSON file.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Pathak Ayush
  • 726
  • 12
  • 24

2 Answers2

0

well, I created a class by which you can create a JSON file then add data to bypassing an array to it and you can update it by replacing data with the new data. check out my code and comment if you don’t understand anything.

it's easy to understand, it's easy to implement.

//  offlineJsonFileManager.swift
//  BuzCard
//
//  Created by ap00724 on 06/02/20.
//  Copyright © 2020 ap00724. All rights reserved.
//

import Foundation
import UIKit

class offlineJsonFileManager: NSObject {

    static let sharedManager = offlineJsonFileManager()

    func saveToJsonFile(fileName:String,dict:[[String:Any]]) {
        guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
        let fileUrl = documentDirectoryUrl.appendingPathComponent("\(fileName).json")

        let personArray = dict

        // Transform array into data and save it into file
        do {
            let data = try JSONSerialization.data(withJSONObject: personArray, options: [])
            try data.write(to: fileUrl, options: [])
        } catch {
            print(error)
        }
    }
    func retrieveFromJsonFile(fileName:String,completion:(Bool,[[String:Any]])->()) {
        // Get the url of Persons.json in document directory
        guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            completion(false,[["error":"file does not exist."]]);return }
        let fileUrl = documentsDirectoryUrl.appendingPathComponent("\(fileName).json")

        // Read data from .json file and transform data into an array
        do {
            let data = try Data(contentsOf: fileUrl, options: [])
            guard let personArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String:Any]] else { return }
            completion(true,personArray)
        } catch {
            print(error)
            completion(false,[["error":"\(error)"]])
        }
    }
}
Pathak Ayush
  • 726
  • 12
  • 24
  • Why a completion handler in the `load` method? Everything is synchronous. And rather than returning an extra `Bool` make the method `throw` and (re)throw the error – vadian Feb 06 '20 at 14:10
  • completion was as per my requirements you can remove if you want. @vadian – Pathak Ayush Feb 07 '20 at 12:36
0
private func saveDomaines(json: [[String: Any]]) {
    if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
        let fileURL = documentsDirectory.appendingPathComponent("domaines.json")
        print("File exists")
        writeFile(fileURL: fileURL, json: json)
    } else {
        print("Shouldn't reach here")
    }
}

private func writeFile(fileURL: URL, json: [[String: Any]]) {
    do {
        if let jsonData = try JSONSerialization.data(withJSONObject: json, options: .init(rawValue: 0)) as? Data {
            try jsonData.write(to: fileURL)
        }
    } catch {
        print(error.localizedDescription)
    }
}