从函数内部的JSON响应更新全局变量 [英] Updating a global variable from JSON response inside function

查看:192
本文介绍了从函数内部的JSON响应更新全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从JSON响应中获取一些变量,并将其显示在自定义表格视图中.问题是这些变量从未更新过..有关更多解释,这是我的代码:

I'm trying to get some variables from JSON response and display it in a custom table view.. the problem is that the variables are never updated.. for more explanations here's my code:

   func getAddresses(){
    let todosEndpoint: String = "my link"
    guard let todosURL = URL(string: todosEndpoint) else {
        print("Error: cannot create URL")
        return
    }
    var todosUrlRequest = URLRequest(url: todosURL)
    todosUrlRequest.httpMethod = "POST"
    todosUrlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
    let newTodo: [String: Any] = ["email": UserDefaults.standard.string(forKey: "email"), "password": UserDefaults.standard.string(forKey: "password")]
    print(newTodo)
    let jsonTodo: Data
    do {
        jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
        todosUrlRequest.httpBody = jsonTodo
    } catch {
        print("Error: cannot create JSON from todo")
        return
    }

    let session = URLSession.shared

    let task = session.dataTask(with: todosUrlRequest) {
        (data, response, error) in
        guard error == nil else {
            print("error calling POST on /public/api/login_customer")
            print(error!)
            return
        }
        guard let responseData = data else {
            print("Error: did not receive data")
            return
        }

        // parse the result as JSON, since that's what the API provides
        do {
            guard let receivedTodo = try JSONSerialization.jsonObject(with: responseData,options: []) as? [String: Any] else {
                print("Could not get JSON from responseData as dictionary")
                return
            }
            print("The todo is: " + receivedTodo.description)

            guard let status = receivedTodo["success"] as? Int else {
                print("Could not get status from JSON")
                return
            }

            if status == 0{
                print("The status is: 0")
                guard let messages = receivedTodo["message"] as? [String:[String]] else {
                    print("Could not get messages from JSON")
                    return
                }
                for (key, value) in messages {
                    var msgs = [String]()
                    msgs.append(value.joined(separator:", "))
                    print("The \(key) error is: " + value.joined(separator:", "))
                }

            }
            else {

                if let address = receivedTodo["address"] as? [[String:Any]] {
                    for info in address {
                        self.label.append(info["label"] as! String)
                        //self.street.append(info["description"] as! String)
                        //self.building.append(info["building_number"] as! String)


                    }
                }
                print("Success!")
            }
        } catch  {
            print("error parsing response from POST on /public/api/login_customer")
            return
        }
    }
    task.resume()
}

这是我在viewDidLoad()中调用以更新这些数组的函数:

This is the function where i'm calling in viewDidLoad() to update these arrays:

var label = [String]()
var street = [String]()
var building = [String]()

我正在使用我的表格视图,例如:

which i'm using with my table view like:

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableview.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomTableViewCell
    cell.label.text=label[indexPath.row]
    cell.street.text=street[indexPath.row]
    cell.buildingno.text=building[indexPath.row]

    return cell
}

我的viewDidLoad:

my viewDidLoad:

 override func viewDidLoad() {
    super.viewDidLoad()

    getAddresses()

    tableview.delegate=self
    tableview.dataSource=self

    tableview.tableFooterView = UIView()
    self.tableview.backgroundColor = UIColor(red:0.96, green:0.96, blue:0.96, alpha:1.0)



    // Do any additional setup after loading the view.
}

问题是这些全局变量从不从getAddresses函数进行更新,并且始终为空..为什么会发生这种情况?以及如何解决?!

The problem is that these global variables are never updated from getAddresses function and its always empty.. why this is happening? and how to solve it?!

推荐答案

在将数据提取到数组中之后,将其写入地址函数中

write this in your address function after fetching the data into your arrays

DispatchQueue.main.async{
    tableView.reloadData()
   }

这篇关于从函数内部的JSON响应更新全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆