下面是我的代码。 此处 print(currency) 函数正在运行。这意味着,检索到了 json 数据。但不显示在表格 View 中。
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")
}
表格 View 部分
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 时。
请帮我加载它。
最佳答案
要获取数据..(您的 NOK 不是字符串..它是 double )
let myJson = try JSONSerialization.jsonObject(with: content, options:[]) as [String:Any]
if let rates = myJson["rates"] as? [String:Double],
let currency = rates["NOK"]
{
print(currency)
self.tableData.append(String(currency))
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
// Declate array of String
var tableData = [String]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = tableData[indexPath.row]
return cell
}
关于ios - 将 JSON 数据加载到 TableView 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41888529/