Search code examples
arraysswiftalamofire

JSON Array to model using Alamofire


I'm creating a UITableView that will display this response in every cell. The problem is, I do not know how to parse this response to the model.

Here is the response from the api

[
"electronics",
"jewelery",
"men's clothing",
"women's clothing"
]

Here is the code for the the ViewController

class HomeViewController: UIViewController {
    
    @IBOutlet var tableView: UITableView!
    var category: [Category] = []
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        
        guard let url = URL(string: "\(Constants.url.baseUrl)\(Constants.url.category)") else {
            return
        }
        
        
        AF.request(url).responseDecodable(of: [Category].self) { response in
            guard let categories = response.value else {
                return
            }
            DispatchQueue.main.async { [weak self] in
                
                self?.tableView.reloadData()
            }
            
            
        }

    }

}

extension HomeViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("category count", category.count)

        return category.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: Constants.identifiers.categoryTableViewCell) as? CategoryTableViewCell else{
            return UITableViewCell()
        }
        cell.configureTableViewCell(with: self.category[indexPath.row])
        return cell

    }


}

Here is my model

struct Category: Codable {
}

I would greatly appreciate any help. Thank you in advanced!


Solution

  • If you really want a model class then decode as already suggested into a String array and then map the result to your model

    struct Category {
        let name: String
    }
    
    AF.request(url).responseDecodable(of: [String].self) { response in
        guard let categories = response.value else {
            return
        }
        DispatchQueue.main.async { [weak self] in
            self.category = categories.map(Category.init)
            self?.tableView.reloadData()
        }
    }