gpt4 book ai didi

ios - 如何在 Swift 2 中从 JSON 填充我的 tableView?

转载 作者:行者123 更新时间:2023-12-01 17:37:35 27 4
gpt4 key购买 nike

新程序员来了。我将如何从这个 JSON 填充我的 tableView?
我的第一个问题是 JSON 序列化,然后将其插入 tableView。

代码

import UIKit

class LegislatorsTableVC: UITableViewController {

// MARK: Variables & Outlets
private let cellIdentifer = "cellReuse"

// MARK: View Did Load
override func viewDidLoad() {
super.viewDidLoad()

// Creating Congfiguration Object // Session Is Created // Getting Info/Data
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration)
let apiKey = "https://congress.api.sunlightfoundation.com/legislators?apikey=xxxxxxxxxxxxxxxxxxxxx&all_legislators=true&per_page=all"

if let url = NSURL(string: apiKey) {
// Spawning Task To Retrieve JSON Data
session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
// Checking For Error
if let error = error {
print("The error is: \(error)")
return
}
// Response
if let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode == 200, let data = data {
print("Status Code: \(httpResponse.statusCode)")
// self.JSONSerialization(data)
}
}).resume()
}
} // End Of View Did Load

// JSON Serialization Function With SwiftyJSON.swift
private func JSONSerialization(data: NSData){

// I See this Gets A Status Code 200 And Then I'm Lost.
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as! [String: AnyObject]

} catch {
print("Error Serializing JSON Data: \(error)")
}
} // End Of JSONSerialization



// MARK: - Table view data source
// Number Of Sections
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
} // End Of Number Of Sections

// Number Of Rows In Section
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 15
} // End Of Number Of Rows In Section

// Cell For Row At Index Path
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifer, forIndexPath: indexPath) as! LegislatorTVCell

// Configure the cell...
cell.name.text = "Name"
cell.title.text = "Title"
cell.party.text = "Party"

return cell
} // End Of Cell For Row At Index Path
}

最佳答案

  • 创建自定义类Person在 View Controller 之外
    class Person {
    var firstName = ""
    var lastName = ""
    var title = ""
    var party = ""
    }
  • 创建 Person 的数组在 View Controller 中
    var people = [Person]()
  • JSON 有一个键 results其中包含一个字典数组。
    viewDidLoad解析 JSON 并创建 Person实例。最后重新加载表格 View 。
    override func viewDidLoad() {
    super.viewDidLoad()

    // Creating Congfiguration Object // Session Is Created // Getting Info/Data
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration)
    let apiKey = "https://congress.api.sunlightfoundation.com/legislators?apikey=xxxxxxxxxxxxxxxxxx&all_legislators=true&per_page=all"

    if let url = NSURL(string: apiKey) {
    // Spawning Task To Retrieve JSON Data
    session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
    // Checking For Error
    if error != nil {
    print("The error is: \(error!)")
    return
    } else if let jsonData = data {
    do {
    let parsedJSON = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! [String:AnyObject]
    guard let results = parsedJSON["results"] as? [[String:AnyObject]] else { return }
    for result in results {
    let person = Person()
    person.firstName = result["first_name"] as! String
    person.lastName = result["last_name"] as! String
    person.party = result["party"] as! String
    person.title = result["title"] as! String
    self.people.append(person)
    }
    dispatch_async(dispatch_get_main_queue()) {
    self.tableView.reloadData()
    }

    } catch let error as NSError {
    print(error)
    }
    }
    }).resume()
    }
    } // End Of View Did Load
  • 使用自定义类时, TableView 委托(delegate)方法看起来非常清晰。
    由于cellForRowAtIndexPath被经常调用的代码是相当有效的。
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
    }

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifer, forIndexPath: indexPath) as! LegislatorTVCell

    let person = people[indexPath.row]
    cell.name.text = person.firstName + " " + person.lastName
    cell.title.text = person.title
    cell.party.text = person.party

    return cell
    } // End

  • 当然我无法测试代码,但这可能是一个起点。

    关于ios - 如何在 Swift 2 中从 JSON 填充我的 tableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35043226/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com