问题
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