我目前正在创建一个用于展示最新足球比分的应用程序。我通过URL连接到API,并将英超联赛的球队名称返回到字符串数组中。
问题似乎出现在我打算使用的iOS表格视图上。数据似乎可以从API正常获取,但由于某种原因,用于创建单元格并返回它的TableView方法似乎没有被调用。唯一可以使该方法被调用的时候是,当我实际硬编码一个值到球队名称数组中。
以下是我的代码:
问题似乎出现在我打算使用的iOS表格视图上。数据似乎可以从API正常获取,但由于某种原因,用于创建单元格并返回它的TableView方法似乎没有被调用。唯一可以使该方法被调用的时候是,当我实际硬编码一个值到球队名称数组中。
以下是我的代码:
class Main: UIViewController {
var names = [String]()
override func viewDidLoad() {
super.viewDidLoad()
let URL_String = "https://football-api.com/api/?Action=standings&APIKey=[API_KEY_REMOVED]&comp_id=1204"
let url = NSURL(string: URL_String)
let urlRequest = NSURLRequest(URL: url!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlRequest, completionHandler: {
(data, response, error) in
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
if let teams = json["teams"] as? [[String : AnyObject]] {
for team in teams {
if let name = team["stand_team_name"] as? String {
self.names.append(name)
}
}
}
} catch {
print("error serializing JSON: \(error)")
}
})
task.resume()
}
// Number of Sections In Table
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
// Number of Rows in each Section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
// Sets the content of each cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = names[indexPath.row]
return cell
}
}
请问有没有人能指点我一下。这段代码不会崩溃或抛出任何错误,但它拒绝加载表视图。我唯一可能想到的原因是,在完成对API的请求后,球队名称数组为空。然而,我已经设置了断点并检查了本地变量的值,所需的信息正在按预期从API中提取...