Swift accessing response from function

前端 未结 1 1988
梦如初夏
梦如初夏 2020-12-22 13:51

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

Array>

相关标签:
1条回答
  • 2020-12-22 14:05

    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.

    0 讨论(0)
提交回复
热议问题