使用Swift从API动态填充iOS表格视图
问题描述:
我目前正在创建应用程序以显示最新的足球比分。我通过一个URL连接到一个API,并将英国首屈一指的团队名称拉回到一串字符串中。使用Swift从API动态填充iOS表格视图
这个问题似乎来自填充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拉...
答
你以正确的方式,使用reloadData
一旦你拿到了刚刚刷新表来自API的新数据
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)
}
}
dispatch_async(dispatch_get_main_queue(), {() -> Void in
self.yourtableViewname.reloadData()
})
}
您应该在有新数据后重新加载表格视图。 –