将JSON数据加载到tableview无法正常工作

时间:2017-01-27 07:06:21

标签: ios json uitableview swift3

以下是我的代码。 这里打印(货币)功能正在运行..这意味着,检索了json数据。但是在表格视图中没有显示。

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时 请帮我加载它。

1 个答案:

答案 0 :(得分:3)

获取数据..(你的NOK不是String ..它的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
}
相关问题