大家好,我是iOS开发的新手,我很难用json数据填充嵌入在UIviewcontroller中的tableview

时间:2016-11-05 21:52:41

标签: json uitableview uiviewcontroller

我是iOS开发的新手,我很难用json数据填充嵌入在UIviewcontroller中的tableview。

''导入UIKit

上课

FirstViewController:UIViewController中,UITableViewDataSource,的UITableViewDelegate {

@IBOutlet weak var tableview: UITableView!
      var TableData:Array< String > = Array < String >()

      var valueToPass:String!


override func viewDidLoad() {

    super.viewDidLoad()


    get_data_from_url("http://www.kaleidosblog.com/tutorial/tutorial.json")

}


override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()


}


func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return TableData.count
}


 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "FirstViewCell", for: indexPath)

    cell.textLabel?.text = TableData[indexPath.row]

    return cell
}



func get_data_from_url(_ link:String)
{
    let url:URL = URL(string: link)!
    let session = URLSession.shared

    let request = NSMutableURLRequest(url: url)
    request.httpMethod = "GET"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData


    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (
        data, response, error) in

        guard let _:Data = data, let _:URLResponse = response  , error == nil else {

            return
        }


        self.extract_json(data!)


    })

    task.resume()

}


func extract_json(_ data: Data)
{


    let json: Any?

    do
    {
        json = try JSONSerialization.jsonObject(with: data, options: [])
    }
    catch
    {
        return
    }

    guard let data_list = json as? NSArray else
    {
        return
    }


    if let countries_list = json as? NSArray
    {
        for i in 0 ..< data_list.count
        {
            if let country_obj = countries_list[i] as? NSDictionary
            {
                if let country_name = country_obj["country"] as? String
                {
                    if let country_code = country_obj["code"] as? String
                    {
                        TableData.append(country_name + " [" + country_code + "]")
                    }
                }
            }
        }
    }





    DispatchQueue.main.async(execute: {self.do_table_refresh()})

}

func do_table_refresh()
{
    tableview.reloadData()

}

}

1 个答案:

答案 0 :(得分:0)

您需要设置tableView的dataSource并委托给self。