gpt4 book ai didi

ios - Swift - 在 vi​​ewDidLoad() 中完成 http 请求之前查看负载

转载 作者:行者123 更新时间:2023-11-28 12:20:42 24 4
gpt4 key购买 nike

我正在尝试从数据库加载一个值,并将它们放入我的一个 Swift 文件中 viewDidLoad 函数的 UITableView 中。调试时,在 View 呈现时,值列表为空,但在 View 加载后,列表会被 View 加载填充。我对 Swift 中的线程没有太多经验,所以我不确定为什么会这样,有什么想法吗?我尝试运行 DispatchQueue.main.async,但没有成功 我的代码如下:

override func viewDidLoad() {

super.viewDidLoad()

// Load any saved meals, otherwise load sample data.
loadDbMeals()

}

private func loadDbMeals() {

var dbMeals = [Meal]()

let requestURL = NSURL(string: self.URL_GET)

let request = NSMutableURLRequest(url: requestURL! as URL)

request.httpMethod = "GET"

//creating a task to send the post request
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in

if error != nil{
print("error is \(String(describing: error))")
return;
}

//parsing the response
do {
//converting response to NSDictionary
let myJSON = try JSONSerialization.jsonObject(with: data!, options: [.mutableContainers]) as? NSDictionary

//parsing the json
if let parseJSON = myJSON {

if let nestedDictionary = parseJSON["message"] as? NSArray {
for meal in nestedDictionary {
if let nestedMeal = meal as? NSDictionary {
let mealName = nestedMeal["name"]
let rating = nestedMeal["rating"]
dbMeals.append(Meal(name: mealName as! String, photo: UIImage(named: "defaultPhoto"), rating: rating as! Int, ingredientList: [])!)

}
}

}

}
} catch {
print(error)
}

}

meals += dbMeals
//executing the task
task.resume()

}

所以,当前的断点顺序,是在viewDidLoad()函数中调用loadDbMeals(),然后尝试将dbMeals变量添加到全局meals变量中,然后执行http请求,空后列表已经添加。感谢您的帮助!

最佳答案

加载数据后重新加载表格

if let parseJSON = myJSON {

if let nestedDictionary = parseJSON["message"] as? NSArray {
for meal in nestedDictionary {
if let nestedMeal = meal as? NSDictionary {
let mealName = nestedMeal["name"]
let rating = nestedMeal["rating"]
dbMeals.append(Meal(name: mealName as! String, photo: UIImage(named: "defaultPhoto"), rating: rating as! Int, ingredientList: [])!)

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

}

关于ios - Swift - 在 vi​​ewDidLoad() 中完成 http 请求之前查看负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44870523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com