Show JSON as TableView Section and TableView row in Swift 4.2 without Decodable?

后端 未结 2 1974
南旧
南旧 2021-01-27 09:06

I have below JSON response array with key \"events\"

{
  \"events\": [
 {
  \"name\": \"event foo\",
  \"date\": \"2020-05-22\",
  \"time\": \"7:00\",
  \"am_or_         


        
2条回答
  •  清歌不尽
    2021-01-27 09:32

    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) 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
       }
    }
    

提交回复
热议问题