我已经构建了一个应用程序,它使用URLsession数据任务从api中提取配方。然后,它获取所有配方名称,并将它们存储在一个字符串数组中。没有嵌套,只有配方名称。我有一个自定义函数来实现这一点。当我调用上述函数时,它会完美地附加到我的全局数组中,但当URLSession数据任务完成时,数组会返回并显示为未受影响。我该如何防止这种情况发生?
以下是我如何申报我的vars
class RecipesVCTableViewController: UITableViewController {
var testArray=[String]()
@IBOutlet var TV: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// where the problem is taking place
testXcode()
// refresh and reload table view cells
TV.reloadData()
//for debugging/breakpoints
print()
}
下面是我的自定义api pull func,它试图附加到testArray:[String]
func testXcode(){
let apiURL = URL(string: "https://api.edamam.com/search?q=mexican&app_id=MYID&app_key=MYAPIKEY")!
let session = URLSession.shared.dataTask(with: apiURL) { (data, response, error) in
let top = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String:Any]
let middle = top["hits"] as? [[String:Any]]
for each in middle!{
// try to append string to string array using hardcode for now
self.testArray.append("Hard code test string.")
self.TV.reloadData()
}
}
session.resume()
}
出于安全原因,我删除了我的apiKey/ID。它仍然在我的应用程序中。
如果在viewDidLoad()
函数中检查print()
的值,则testArray
将是相同的,因为dataTask
的completionHandler
尚未被调用。您应该检查completionHandler
中的值,如下所示。
class RecipesVCTableViewController: UITableViewController {
var testArray=[String]()
@IBOutlet var TV: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// where the problem is taking place
testXcode()
}
func testXcode() {
let apiURL = URL(string: "https://api.edamam.com/search?q=mexican&app_id=MYID&app_key=MYAPIKEY")!
let session = URLSession.shared.dataTask(with: apiURL) { (data, response, error) in
let top = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String:Any]
let middle = top["hits"] as? [[String:Any]]
for each in middle!{
// try to append string to string array using hardcode for now
self.testArray.append("Hard code test string.")
}
self.TV.reloadData()
// Check it from here
print()
}
session.resume()
}
}