如何用Swift 3中的JSON数据填充表格?

时间:2017-01-02 18:37:31

标签: ios json swift tableview alamofire

我创建了一个tableView,其中我想使用此链接放置新闻

   https://api.sis.kemoke.net/news

有三件事我想得到并填充表格。

    String title
    String text
    String link

这是我的班级

    import Alamofire //Framework for handling http requests
    import UIKit

/ 一个类,它将处理http请求,以字符串形式接收新闻并用数据填充数组,这些数据将显示在表中 / class NewsTableViewController:UITableViewController {

//Array which holds the news
var newsData:Array< String > = Array < String >()

// Download the news
func downloadData() {
    Alamofire.request("https://api.sis.kemoke.net/news").responseJSON { response in
        print(response.request)  // original URL request
        print(response.response) // HTTP URL response
        print(response.data)     // server data
        print(response.result)   // result of response serialization

        //Optional binding to handle exceptions
        if let JSON = response.result.value {
            print("JSON: \(JSON)")
        }
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    downloadData()
    extractData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

// MARK: - Table view data source
// Number of sections i table vie
override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

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


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = newsData[indexPath.row]
    return cell
}

// Extract the data from the JSON
func extractData() {
    Alamofire.request("https://api.sis.kemoke.net/news").responseJSON { response in
        debugPrint(response)

        if let json = response.result.value {
            print("JSON: \(json)")
            self.newsData = json as! Array
        }
    }
}

// MARK: - Navigation

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}

}

稍后我会尝试获取图像,但现在这三个变量应该足够了。

1 个答案:

答案 0 :(得分:1)

  • 首先为数据创建自定义结构

    struct News {
      let title : String
      let text : String
      let link : String
    
      init(dictionary: [String:String]) {
         self.title = dictionary["title"] ?? ""
         self.text = dictionary["text"] ?? ""
         self.link = dictionary["link"] ?? ""
      }
    }
    
  • 数据源数组是

    var newsData = [News]() 
    
  • 仅使用 downloadData(),删除其他方法 使用自定义结构,解析非常简单:

    func downloadData() {
        Alamofire.request("https://api.sis.kemoke.net/news").responseJSON { response in
            print(response.request)  // original URL request
            print(response.response) // HTTP URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization
    
            //Optional binding to handle exceptions
            if let json = response.result.value as? [[String:String]] {
                self.newsData = json.map{ News(dictionary: $0) }
                self.tableView.reloadData()
            }
        }
    }
    
  • cellForRow...中显示标题

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let news = newsData[indexPath.row]
        cell.textLabel?.text = news.title
        return cell
    }