Read a local file to Json

func fetch(withTestJson file: String) -> Array<LineModel>? {
    // get path
    guard let path = Bundle.main.path(forResource: file, ofType: "json") else {
        print("BaseD.C: not such testJson file")
        return nil
    }
    // get data json
    let jsonData = try! Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
    let json = try! JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves)
    // parse json
    guard let lines = json as? Dictionary<String, Any>,
        let linesData = lines[LinesKey.lines]
        else {
            return nil
        }
    // to models
    var models = Array<LineModel>()
    if let jsonArray = linesData as? Array<Any> {
        for element in jsonArray {
            if let modelDict = element as? Dictionary<String, AnyObject>,
                let model = LineModel(dict: modelDict) {
                models.append(model)
            }
        }
    }
    return models
}

func fetch(withFile file: String, ext: String) {
    // willnot retain cycle forever, after return block, retain cycle break
    DispatchQueue.global().async {
        guard let lines = self.dataController.fetch(withFile: file, ext: ext) else {
            return
        }
        print("SubwayL.VC: fetched \(lines.count)")
        DispatchQueue.main.async {
            self.lines = lines
        }
    }
}

results matching ""

    No results matching ""