我正在尝试创建一个使用在线休息API的应用程序。它通过URLSession
检索数据。在do{}
方法中,正确填充整个数组。但是,当我返回数组时,突然之间它完全是空的。有人可以向我解释我做错了吗?
// Makes a request to the API
func makeRequest(url: URL) -> Array<Any>{
var allItems = [[ApiItem]]()
// Make request
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
// Do the request
do{
// Get the JSON
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: AnyObject]
// Get the right entry
let results = json["items"] as? [AnyObject]
// Loop through the results
for r in results! {
// Create a item
let item = ApiItem(json: r as! [String : Any])
// Add them to the array
allItems.append([item])
print("Items in array after appending: \(allItems.count)") // The entire array gets correctly filled here
}
} catch let jsonErr{
print("JSON ERROR! \(jsonErr)")
}
}.resume()
return allItems // The array is empty right here
}