在将JSON数据导出到文本字段中时出现问题

时间:2019-05-09 21:06:04

标签: ios json swift

我正在使用JSONDecoder协议从数据库中获取一些数据。

以下所有代码均按预期工作,但我无法让car.driver_name导出到名为contacttextField的文本字段中

我尝试将self.contacttextField = car.driver_name设置为较差的结果。由于某种原因,解码后的JSON中的文本显示大约需要一分钟,调试器会说:

10  Foundation                          0x00000001d67a8908 <redacted> + 740
11  Foundation                          0x00000001d689ecec <redacted> + 272
12  libdispatch.dylib                   0x0000000102a436f0 _dispatch_call_block_and_release + 24
13  libdispatch.dylib                   0x0000000102a44c74 _dispatch_client_callout + 16
14  libdispatch.dylib                   0x0000000102a47ffc _dispatch_continuation_pop + 524
15  libdispatch.dylib                   0x0000000102a47458 _dispatch_async_redirect_invoke + 628
16  libdispatch.dylib                   0x0000000102a55dc8 _dispatch_root_queue_drain + 372
17  libdispatch.dylib                   0x0000000102a567ac _dispatch_worker_thread2 + 156
18  libsystem_pthread.dylib             0x00000001d5a591b4 _pthread_wqthread + 464
19  libsystem_pthread.dylib             0x00000001d5a5bcd4 start_wqthread + 4

以下是我正在使用的代码:

struct FacilityInfo: Decodable {
    let driver_name: String
}

class infoViewController: UIViewController {
    @IBOutlet weak var usernameTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "https://example.com/example/test.php")!

        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            // ensure there is no error for this HTTP response
            guard error == nil else {
                print ("error: \(error!)")
                return
            }

            // ensure there is data returned from this HTTP response
            guard let data = data else {
                print("No data")
                return
            }

            // Parse JSON into array of Car struct using JSONDecoder

            guard let cars = try? JSONDecoder().decode([FacilityInfo].self, from: data) else {
                print("Error: Couldn't decode data into cars array")
                return
            }

            for car in cars {
                print("car name is \(car.driver_name)")
                self.usernameTextField.text = cars.driver_name
            }
        }

        task.resume()

1 个答案:

答案 0 :(得分:0)

URLSession.dataTask在后​​台线程上执行其关闭,但是所有UI更新都需要在主线程上进行。因此,您需要在主线程上执行对usernameTextField.text的调用。

...
guard let cars = try? JSONDecoder().decode([FacilityInfo].self, from: data), let firstCar = cars.first else {
    print("Error: Couldn't decode data into cars array")
    return
}
DispatchQueue.main.async {
    self.usernameTextField.text = firstCar.driver_name
}

还要记住,cars是一个数组,因此您应该访问其元素之一,该元素具有driver_name属性,并将其分配给文本字段的text属性。例如,我已经从第一个元素中分配了值,但是根据您的要求进行了更改。

您还应该遵守Swift命名约定,即变量名(driverName)的lowerCamelCase。