从结构中获取数据以在表视图中使用

时间:2019-01-29 22:22:36

标签: swift macos

我无法获得包含从JSON加载为适用于表格视图格式的var的结构

我已经在这段代码中玩了一段时间了,做了很多阅读,但是我还是很固执。我可以很好地从服务器获取数据并将其打印到控制台。我注意到数据以KEY:“ value”而不是“ KEY”:“ value”的形式打印,这可能与它有关。同样由于代码是正确的,所以我可以正确计算行数并在表视图中显示FIRST的值。我不知道的是如何访问其他变量进行显示。任何帮助将不胜感激!

import Cocoa

class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {

static var globalPatientInstance: [Patient] = []

var gotJSON: ([Patient], Error?) -> Void = { (patients, error) in
    print("patients from gotJSON: \(patients)")

    globalPatientInstance = patients

    // this returns an error: "Type 'Patient' does not conform to protocol 'Sequence'"
    /*
     for (key, value) in patients[0] {
     println("\(key) -> \(value)")
     tableArray.append(Objects(sectionName: key, sectionObjects: value))
     }
     */
    print("patients from gotJSON: \(globalPatientInstance[0])")
}

@IBOutlet var tableView: NSTableView!
@IBAction func button(_ sender: Any) {
    self.tableView.reloadData()
}


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.tableView.delegate = self as NSTableViewDelegate
    self.tableView.dataSource = self

    let url = URL(string: "http://172.16.1.25/backend/returnA")
    let returnA = URLRequest(url: url!)

    retrieveJSON(with: returnA, completionHandler: gotJSON)
    self.tableView.reloadData()
}


func retrieveJSON(with request: URLRequest, completionHandler: @escaping ([Patient], Error?) -> Void) {

    // set up the session
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    // make the request
    let task = session.dataTask(with: request as URLRequest) {

        // completion handler argument
        (data, response, error) in

        // completion handler
        guard let data = data else {
            print("Did not recieve data")
            completionHandler([], error)
            return
        }
        do {
            let decoder = JSONDecoder()
            let patients = try decoder.decode(Array<Patient>.self, from: data)
            // print(Patient)
            completionHandler(patients, error)
        }
        catch let err {
            print("Err", err)
            completionHandler([], error)
        }
    }
    task.resume()
}


func numberOfRows(in tableView: NSTableView) -> Int {
    return ViewController.globalPatientInstance.count
}

func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {

    var result: NSTableCellView


    result = tableView.makeView(withIdentifier: (tableColumn?.identifier)!, owner: self) as! NSTableCellView

    result.textField?.stringValue = ViewController.globalPatientInstance[row].FIRST

    return result
}
}

此代码运行良好。数组包含三个结构,按下按钮后,FIRST的值将成功显示在表格视图中。

0 个答案:

没有答案