swiftuitableviewuiviewcontrolleralamofireswifty-json

how to populate cells in a UItableview with switfyJson from an alamofire post request


I have a Tableviewcontroller embedded in a Viewcontroller. And i would like to populate this 3 cells with data from my alamofire post request. whats the easiest way to get that done? i can see my alamofire post request printed in the debug area. so far i came till now.

enter image description here the viewcontroller looks like this.

import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController {
    
    @IBOutlet weak var tableViewScore: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        getScores()
        tableViewScore.delegate = self
        tableViewScore.dataSource = self
    }

}

public func getScores() {

    let URL_SCORES = "http://localhost/projecttitle/v1/scores.php"

    let username = "username@projecttitle.com"
        
        //creating parameters for the post request for now.
        let parameters: Parameters=[
            "username":username
        ]
        
        //Sending http post request
        AF.request(URL_SCORES, method: .post, parameters: parameters).responseJSON
        {
                response in
                //printing response
                print(response)
                
                switch response.result {
                    case .success (let value):
                    let json = JSON(value)
                    
                    for (key,subJson):(String, JSON) in json["scores"] {
                        debugPrint (key) //key
                        debugPrint (subJson) //value
                            
                        debugPrint (subJson["date"]) //value
                        debugPrint (subJson["coursename"]) //value
                        debugPrint (subJson["score"]) //value

                    }
                        case .failure(let error):
                        print(error)
                    }
    }
}

extension ViewController : UITableViewDataSource{
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
       return count 
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCellScores
        
        // populate the cells with date, coursename and score

        return cell
    }
}
extension UIViewController : UITableViewDelegate{
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
}

the UITableViewCell looks like this.

import UIKit

class TableViewCellScores: UITableViewCell {
    
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var courseNameLabel: UILabel!
    @IBOutlet weak var scoreLabel: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

Solution

  • You can create a Model named "MyModel" at the outside of your view controller :

    struct MyModel {
        let date: String?
        let coursename: String?
        let score: String?
    }
    

    And at your view controller define a variable:

    var myModel = [MyModel]()
    

    At your getScores() func fill your model :

    for (key,subJson):(String, JSON) in json["scores"] {
        debugPrint (key) //key
        debugPrint (subJson) //value
                                
        debugPrint (subJson["date"]) //value
        debugPrint (subJson["coursename"]) //value
        debugPrint (subJson["score"]) //value
    
        self.myModel.append(date: subJson["date"], coursename: subJson["coursename"], score: subJson["score"])
    }
    
    tableViewScore.reloadData() //reload your tableview end of the for loop 
    

    Return self.myModel.count at your numberOfRowsInSection func

    At cellForRowAt :

    cell.dateLabel.text = self.myModel[indexPath.row].date