【问题标题】:How to fill table with JSON data in Swift 3?如何在 Swift 3 中用 JSON 数据填充表格?
【发布时间】:2017-01-02 18:37:31
【问题描述】:

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

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

我想要获取并填充表格中的三件事。

    String title
    String text
    String link

这是我的课

    import Alamofire //Framework for handling http requests
    import UIKit

/一个类,它将处理 http 请求,以字符串形式接收新闻,并用这些数据填充数组,这些数据将显示在一个表格中/ 类 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.
}

}

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

【问题讨论】:

  • 为什么你有两种方法(extractDatadownloadData)都做同样的事情?为什么都从viewDidLoad 调用?为什么其中任何一个都不重新加载表格?
  • @rmaddy 我认为有必要从 viewDidLoad 调用它们。这是由于我缺乏经验,因为我是移动应用程序开发的新手。请您解释一下如何解决我的问题?

标签: ios json swift tableview alamofire


【解决方案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
    } 
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多