ios - 从函数内的 JSON 响应更新全局变量

标签 ios json swift xcode tableview

我试图从 JSON 响应中获取一些变量并将其显示在自定义 TableView 中。问题是这些变量永远不会更新。更多解释是我的代码:

   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() 中调用来更新这些数组的函数:

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

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

   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:

 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 函数中更新,并且始终为空。为什么会发生这种情况?以及如何解决?!

最佳答案

将数据提取到数组后将其写入地址函数

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

关于ios - 从函数内的 JSON 响应更新全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52749541/

相关文章:

ios - 投影矩阵有什么用?

json - 如何解析从 SOAP WS 的 XML 响应创建的 JSON?

c# - 如何将 JSON 转换为 C# 字典?

ios - 停止 Segue 并传递到下一个查看警报中显示的文本字段的内容 - Swift

ios - 通过同一触摸在 View 上的手势之间切换

ios - 寻找 NSMutableDate 类

ios - UIScrollView - 像 iOS 7 邮件应用程序一样通过触摸拖动移动键盘?

java - 消息负载的类型为 : BufferInputStream

arrays - 数组中第一个对象的 Swift 数组

iphone - 如果您使用的是 iOS 5.1,我希望此按钮显示一条错误消息