首先,您需要创建一个模型,以便将您的 JSON 转换为可用的对象。为此,好的做法是使用 Codable 协议,它会自动将您的 JSON 键映射到结构/类变量
struct Event: Codable {
var name: String!
var date: String!
var time: String!
var am_or_pm: String!
var day: String!
var description: String!
}
struct Events: Codable {
var events: [Event]!
}
现在您已经有了将从 JSON 生成的模型,您需要将 JSON 解码为您的模型。有很多方法可以做到,我喜欢使用 JSONEncoder/JSONDecoder。
因此,假设您的 JSON 字符串存储在变量 myJsonString 中,您需要
if let jsonData = myJsonString.data(using: .utf8) {
do {
let events = try JSONDecoder().decode(Events.self, from: jsonData)
} catch {
print("Error decoding json!", error.localizedDescription)
}
} else {
print("Failed to get bytes from string!")
}
现在,我们可以将该代码块转换为返回事件的函数,如果它无法解码字符串,则返回 nil。
func getEvents(from jsonString: String) -> Events? {
guard let jsonData = myJsonString.data(using: .utf8) else { return nil }
return try? JSONDecoder().decode(Events.self, from: jsonData)
}
酷!我们现在可以轻松地基于 JSON 字符串获取我们的事件!我们接下来要做的就是填充 tableView!
为此,我们可以在 Events 结构中创建一些函数,这些函数将返回填充我们部分所需的内容。第一个函数将返回我们的 tableView 的部分,第二个函数将返回给定部分的所有项目。让我们修改Events 结构体
struct Events: Codable {
var events: [Event]!
func getSections() -> [String] {
return Array(Set(self.events.map { $0.date }))
}
func getItems(forSection dateSection: String) -> [Section] {
return self.events.filter {$0.date == dateSection}
}
}
现在,在您的 TableView 数据源类中,您需要使用我们创建的模型。我给你举个例子
class YourTableView: UIViewController, UITableViewDataSource, UITableViewDelegate {
// This is loaded from the getEvents function!
var events: Events!
func numberOfSections (in tableView: UITableView) -> Int {
return self.events.getSections().count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let dateSection = self.events.getSections()[section]
return self.events.getItems(forSection: dateSection ).count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dateSection = self.events.getSections()[indexPath.section]
let currentEvent = self.getItems(forSection: dateSection)
// Build your cell using currentEvent
}
}
您可能从 Web 获取这些 JSON,因此您必须处理“加载”状态,即从 API 返回 JSON。这可以通过将events var 转换为可选项,在获取 JSON 并从 tableView 重新加载数据时设置它来轻松完成