gpt4 book ai didi

ios - 第一次单击按钮时未显示数据

转载 作者:行者123 更新时间:2023-11-28 11:31:22 26 4
gpt4 key购买 nike

我的应用程序正在解码来自 PHP 网络服务的一些 JSON 数据,但是当我第一次点击获取按钮时,数据没有显示在标签上。

在调试中,我可以看到数据已传递到数组,但未传递到 View Controller 中的标签。

你能帮我解决这个问题吗?

提前致谢

阿德尔莫

点击按钮

@IBAction func btn_ler(_ sender: Any)
{

//txt_matricula.text = ""
//txt_marca.text = ""
//txt_modelo.text = ""

obter_dados_veiculo(matricula: input_matricula.text!)

for veiculo in a_veiculos
{
txt_matricula.text = veiculo.MATRICULA
txt_modelo.text = veiculo.MODELO
txt_marca.text = veiculo.MARCA
}

//lbl_num_servicos.text = String( a_veiculos.count)
}

获取JSON的函数

func obter_dados_veiculo (matricula : String)
{
//Variável que vai conter o URL
let v_url = "http://arshome.hopto.org/Domingues/DEV/api_get_veiculos.php?MATRICULA=" + matricula

let o_url = URL(string: v_url)

URLSession.shared.dataTask(with: o_url!)
{
(data, response, error) in

do
{
let matriculas = try JSONDecoder().decode([s_veiculo].self, from: data!)


//for matricula in matriculas
//{
//print(matricula.MATRICULA)
a_veiculos = []
a_veiculos.append(contentsOf: matriculas)
//}
}
catch
{
print("We have an error!")
//self.txt_matricula.text = "We have an error!"
}
print( a_veiculos.count)
}.resume()
}

最佳答案

你必须在你的obter_dados_veiculo方法中添加一个完成闭包,如下所示:

func obter_dados_veiculo (matricula : String, completion:@escaping(Bool,Error?)->())
{
//Variável que vai conter o URL
let v_url = "http://arshome.hopto.org/Domingues/DEV/api_get_veiculos.php?MATRICULA=" + matricula

let o_url = URL(string: v_url)

URLSession.shared.dataTask(with: o_url!)
{
(data, response, error) in

do
{
let matriculas = try JSONDecoder().decode([s_veiculo].self, from: data!)


//for matricula in matriculas
//{
//print(matricula.MATRICULA)
a_veiculos = []
a_veiculos.append(contentsOf: matriculas)
completion(true,nil)
//}
}
catch let error as NSError
{
print("We have an error!")
completion(false,error)
//self.txt_matricula.text = "We have an error!"
}
print( a_veiculos.count)
}.resume()
}

然后像下面这样调用它:

@IBAction func btn_ler(_ sender: Any)
{

//txt_matricula.text = ""
//txt_marca.text = ""
//txt_modelo.text = ""

obter_dados_veiculo(matricula: input_matricula.text!) { (success, error) in
for veiculo in self.a_veiculos
{
txt_matricula.text = veiculo.MATRICULA
txt_modelo.text = veiculo.MODELO
txt_marca.text = veiculo.MARCA
}
}

//lbl_num_servicos.text = String( a_veiculos.count)
}

关于ios - 第一次单击按钮时未显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56645404/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com