在 Swift 4.2 中将 JSON 显示为 TableView 部分和 TableView 行而没有可解码? [英] Show JSON as TableView Section and TableView row in Swift 4.2 without Decodable?
问题描述
我有以下带有关键事件"的 JSON 响应数组
<代码>{事件":[{"name": "事件 foo","日期": "2020-05-22","时间": "7:00","am_or_pm": "下午","day": "星期六",描述":测试"},{"name": "事件栏","日期": "2020-05-22","时间": "7:00","am_or_pm": "下午","day": "星期六",描述":测试2"},{"name": "事件 foobar","日期": "2020-05-24","时间": "11:00","am_or_pm": "下午","day": "星期六",描述":测试3"},{"name": "事件 foobar","日期": "2020-05-24","时间": "11:00","am_or_pm": "下午","day": "星期六",描述":测试3"}]}
我想在 TableView 中将上面的 JSON 响应显示为:date"键应该是TableView Section分组,Rows应该是name"键
可以帮我吗,我将如何做到这一点,提前致谢.
我使用 Alamofire 5.0
完成了上述解决方案,以下是我的完整解决方案,以便它可以帮助某人:
//创建一个名为Event"的模态类
class 事件 {变量名称:字符串?var 日期:字符串?变量时间:字符串?var amOrPm:字符串?var day:字符串?变量描述:字符串?init(dic: [字符串: 任何]) {if let name = dic["name"] as?细绳 {self.name = 姓名}if let date = dic["date"] as?细绳 {self.date = 日期}if let time = dic["time"] as?细绳 {self.time = 时间}如果让 amOrPm = dic["am_or_pm"] 作为?细绳 {self.amOrPm = amOrPm}如果让 day = dic["day"] 作为?细绳 {self.day = 天}if let description = dic["description"] as?细绳 {self.description = 描述}}}
<块引用>
//为 URL 创建全局类
import Alamofire类 HttpManager {结构常量{static let baseUrl = "https://my-json-server.typicode.com/JCkshone/jsonTest"}func getEvents(handledResponse: @escaping (_ data: [[String: Any]])->()) {让请求 = AF.request("\(Constants.baseUrl)/db")request.responseJSON { (response: AFDataResponse) in守卫让数据= response.value as?[字符串:任何]其他{返回}if let events: [[String: Any]] = data["events"] as?[[字符串:任意]] {处理响应(事件)}}}}
//最后是 ViewController.swift
struct SectionEvent {var 部分名称:字符串var event: [事件]}类视图控制器:UIViewController {@IBOutlet 弱变量 tableView:UITableView!让 http = HttpManager()var 事件:[事件] = []var tableViewData: [SectionEvent] = []让单元格 = "cellId"覆盖 func viewDidLoad() {super.viewDidLoad()获取数据()initTableView()}功能 fetchData() {http.getEvents { (data: [[String : Any]]) 在data.forEach { 项目在self.events.append(Event(dic: item))}self.buildData()}}功能构建数据(){events.forEach { 事件在让验证 = validateEventExist(事件:事件)如果 !validation.exist {tableViewData.append(SectionEvent(sectionName: event.date ?? "", event: [event]))} 别的 {tableViewData[validation.position].evenst.append(event)}}self.tableView.reloadData()}func validateEventExist(event: Event) ->(存在:布尔,位置:整数){让 filterData = tableViewData.filter {$0.sectionName == event.date}让 index = tableViewData.firstIndex { $0.sectionName == event.date}返回 (filterData.count > 0, index ?? 0)}func initTableView() {tableView.register(UITableViewCell.self, forCellReuseIdentifier: cell)tableView.tableHeaderView = UIView()}}扩展视图控制器:UITableViewDataSource,UITableViewDelegate {func tableView(_ tableView: UITableView, titleForHeaderInSection 部分: Int) ->细绳?{tableViewData[section].sectionName}func numberOfSections(in tableView: UITableView) ->整数{tableViewData.count}func tableView(_ tableView: UITableView, numberOfRowsInSection 部分: Int) ->整数{tableViewData[section].evenst.count}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->UITableViewCell {let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)if let name = tableViewData[indexPath.section].evenst[indexPath.row].name, let description = tableViewData[indexPath.section].evenst[indexPath.row].description {cell.textLabel?.text = "\(name) \n\(description)"cell.textLabel?.numberOfLines = 0}返回单元格}}
I have below JSON response array with key "events"
{
"events": [
{
"name": "event foo",
"date": "2020-05-22",
"time": "7:00",
"am_or_pm": "PM",
"day": "Saturday",
"description": "test "
},
{
"name": "event bar",
"date": "2020-05-22",
"time": "7:00",
"am_or_pm": "PM",
"day": "Saturday",
"description": "test2"
},
{
"name": "event foobar",
"date": "2020-05-24",
"time": "11:00",
"am_or_pm": "PM",
"day": "Saturday",
"description": "test3"
},
{
"name": "event foobar",
"date": "2020-05-24",
"time": "11:00",
"am_or_pm": "PM",
"day": "Saturday",
"description": "test3"
}
]
}
I want to show above JSON response in TableView as : "date" key should be TableView Section grouped and Rows as "name" key
Could some help me how will i do that thanks in advance.
I did above solutions using Alamofire 5.0
and below is my complete solutions so that it can help someone:
// Create a Modal Class of name "Event"
class Event {
var name: String?
var date: String?
var time: String?
var amOrPm: String?
var day: String?
var description: String?
init(dic: [String: Any]) {
if let name = dic["name"] as? String {
self.name = name
}
if let date = dic["date"] as? String {
self.date = date
}
if let time = dic["time"] as? String {
self.time = time
}
if let amOrPm = dic["am_or_pm"] as? String {
self.amOrPm = amOrPm
}
if let day = dic["day"] as? String {
self.day = day
}
if let description = dic["description"] as? String {
self.description = description
}
}
}
// Creating a Global Class for URL
import Alamofire
class HttpManager {
struct Constants {
static let baseUrl = "https://my-json-server.typicode.com/JCkshone/jsonTest"
}
func getEvents(handledResponse: @escaping (_ data: [[String: Any]])->()) {
let request = AF.request("\(Constants.baseUrl)/db")
request.responseJSON { (response: AFDataResponse<Any>) in
guard let data = response.value as? [String: Any] else { return }
if let events: [[String: Any]] = data["events"] as? [[String: Any]] {
handledResponse(events)
}
}
}
}
// Finally ViewController.swift
struct SectionEvent {
var sectionName: String
var evenst: [Event]
}
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
let http = HttpManager()
var events: [Event] = []
var tableViewData: [SectionEvent] = []
let cell = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
initTableView()
}
func fetchData() {
http.getEvents { (data: [[String : Any]]) in
data.forEach { item in
self.events.append(Event(dic: item))
}
self.buildData()
}
}
func buildData() {
events.forEach { event in
let validation = validateEventExist(event: event)
if !validation.exist {
tableViewData.append(SectionEvent(sectionName: event.date ?? "", evenst: [event]))
} else {
tableViewData[validation.position].evenst.append(event)
}
}
self.tableView.reloadData()
}
func validateEventExist(event: Event) -> (exist: Bool, position: Int) {
let filterData = tableViewData.filter {$0.sectionName == event.date}
let index = tableViewData.firstIndex { $0.sectionName == event.date}
return (filterData.count > 0, index ?? 0)
}
func initTableView() {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cell)
tableView.tableHeaderView = UIView()
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
tableViewData[section].sectionName
}
func numberOfSections(in tableView: UITableView) -> Int {
tableViewData.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableViewData[section].evenst.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
if let name = tableViewData[indexPath.section].evenst[indexPath.row].name, let description = tableViewData[indexPath.section].evenst[indexPath.row].description {
cell.textLabel?.text = "\(name) \n\(description)"
cell.textLabel?.numberOfLines = 0
}
return cell
}
}
这篇关于在 Swift 4.2 中将 JSON 显示为 TableView 部分和 TableView 行而没有可解码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!