Swift accessing response from function

送分小仙女□ 提交于 2019-11-28 14:14:10

问题


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

Array<Dictionary<String,String>>

I have a class:

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 returns nil. My goal is to have an array of jsonData so i can use .count method on it.


回答1:


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.

Let's look at your code:

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
}   


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.



来源:https://stackoverflow.com/questions/47297849/swift-accessing-response-from-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!