【发布时间】:2017-06-12 19:31:46
【问题描述】:
下面是我的代码。 这里 print(currency) 函数正在工作..这意味着检索到 json 数据。但不显示在 tableview 中。
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var TableData:Array< String > = Array < String >()
override func viewDidLoad()
{
super.viewDidLoad()
get_data_from_url("http://api.fixer.io/latest")
}
表格视图部分
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return(TableData.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = TableData[indexPath.row]
return (cell)
}
JSON 数据检索
func get_data_from_url(_ link:String)
{
let url = URL(string: "http://api.fixer.io/latest")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print ("ERROR")
}
else
{
if let content = data
{
do
{
//Array
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if let rates = myJson["rates"] as? NSDictionary
{
if let currency = rates["NOK"] as? String
{
print(currency)
self.TableData.append(currency)
self.tableView.reloadData()
}
}
}
catch
{
}
}
}
}
task.resume()
}
数据显示在带有打印功能的 xcode 中。所以很明显,数据正在检索。但问题是在将数据加载到 tableview 时。
请帮我加载它。
【问题讨论】:
-
从 tableView 方法中删除
public还要检查您的tableViewdelegate和dataSourece是否与您的 viewController 正确连接。 -
再次它不起作用@NiravD
-
像
DispatchQueue.main.async { self.tableView.reloadData() }一样在主线程上重新加载tableView -
对不起。挪威克朗是双倍的。下面的答案有帮助。感谢您的帮助@NiravD
标签: ios json uitableview swift3