快速访问功能的响应 [英] Swift accessing response from function

查看:100
本文介绍了快速访问功能的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在生成一个GET请求,该请求以以下格式为我提供了字典中数组的JSON对象:

I am producing a GET request, which gives me JSON object of array within dictionaries in this format:

Array<Dictionary<String,String>>

我有一堂课:

class foodMenu: UITableViewController{

    var jsonData:Array<Dictionary<String,String>>! // Here is set an empty global variable(Not sure if I am doing this right either)

    func getFoodRequest(){
        Alamofire.request("http://127.0.0.1:5000/get_food").responseJSON {
            response in
            print("This response", response.result)
            let result = response.result.value
            self.jsonData = result as! Array<Dictionary<String,String>>
        }
   }

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   getFoodRequest()        
   return jsonData!.count
  }   
}

jsonData返回nil。我的目标是拥有一个 jsonData 数组,以便可以在其上使用.count方法。

jsonData returns nil. My goal is to have an array of jsonData so i can use .count method on it.

推荐答案

问题是您尝试同步进行网络连接,但不能。实际上,您是异步联网的,这是正确的,但是您忘记了联网是异步的。

The problem is that you are trying to network synchronously, and you can't. Actually, you are networking asynchronously, which is correct, but you are forgetting that networking is asynchronous.

让我们看看您的代码:

func getFoodRequest(){
    Alamofire.request("http://127.0.0.1:5000/get_food").responseJSON {
        response in
        let result = response.result.value
        self.jsonData = result as! Array<Dictionary<String,String>> // B
    }
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    getFoodRequest() // A      
    return jsonData!.count // C
}   


看一下我添加的字母注释。您似乎认为代码按A,B,C顺序执行。没错它以A,C,B的顺序执行。那是因为让您的响应花费时间并在后台线程上发生,同时您的 numberOfRowsInSection 一直在执行并执行下一行并完成。


Look at the letter comments I've added. You seem to think that the code executes in the order A,B,C. It doesn't. It executes in the order A,C,B. That's because getting your response takes time and happens on a background thread, and meanwhile your numberOfRowsInSection has gone right ahead and executed the next line and finished.

这篇关于快速访问功能的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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