1

I am using this api and want to print the api data on table view

     import UIKit
     import Alamofire

     class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

      @IBOutlet weak var tableView: UITableView!
     @IBOutlet weak var mySegmentedControl: UISegmentedControl!





override func viewDidLoad() {
    super.viewDidLoad()

    apiData()
}

@IBAction func mySegmentControlTapped(_ sender: Any) {
    tableView.reloadData()
}


func apiData() {
    Alamofire.request("https://api.lrs.org/random-date-generator?lim_quarters=40&source=api-docs", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

        switch(response.result) {
        case .success(_):
            guard let json = response.result.value as? [String:Any] else{ return}
            print("Response \(json)")
            guard let data = json["data"] as? [String:Any] else { return}
            print("data is \(data)")

            for (key, value) in data {
                print("\(key) -> \(value)")


            }

            break

        case .failure(_):
            print(response.result.error as Any)
            break

        }
    }

}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    var returnValue = 0

    switch(mySegmentedControl.selectedSegmentIndex)
    {
    case 0:
        returnValue = day.count
        break
    case 1:
        returnValue = month.count
        break

    case 2:
        returnValue = db.count
        break

    case 3:
        returnValue = day.count
        break

    default:
        break

    }

    return returnValue
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let myCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! tableCell

    switch(mySegmentedControl.selectedSegmentIndex)
    {
    case 0:
        myCell.labelOne!.text = " "
        myCell.labelTwo!.text = ""
        myCell.labelThree!.text = ""
        myCell.labelFour!.text = ""
        break
    case 1:

        break

    case 2:

        break

    case 3:

        break

    default:
        break

    }
    return myCell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 90
}


}

class tableCell: UITableViewCell {

@IBOutlet weak var labelOne: UILabel!
@IBOutlet weak var labelTwo: UILabel!
@IBOutlet weak var labelThree: UILabel!
@IBOutlet weak var labelFour: UILabel!

   }

After using this code I am getting the keys and values my question is I am getting the 6 value in 1 key. How can I store all these values and print it on tableview. This is my whole code I am doing I am using segment controller to change the data according to date months enter image description here

viper
  • 141
  • 1
  • 3
  • 16

4 Answers4

2

First create a class to model the response:

class CustomDate: NSObject {
    var quarter: Int!
    var day: String!
    var month: String!
    var db: String!
    var long: String!
    var unix: Int!

    init(quarter: Int, day: String, month: String, db: String, long: String, unix: Int) {
        super.init()

        self.quarter = quarter
        self.day = day
        self.month = month
        self.db = db
        self.long = long
        self.unix = unix
    }
}

Then create an array to store all the received dates:

var dates = [CustomDate]()

Change the implementation of apiData to this:

func apiData() {
    Alamofire.request("https://api.lrs.org/random-date-generator?lim_quarters=40&source=api-docs", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

        switch(response.result) {
        case .success(_):
            guard let json = response.result.value as? [String: Any] else { return }
            guard let data = json["data"] as? [String: Any] else { return }

            for (_, value) in data {
                let dateValue = value as! [String: Any]
                let date = CustomDate(quarter: dateValue["quarter"] as! Int,
                                      day: dateValue["day"] as! String,
                                      month: dateValue["month"] as! String,
                                      db: dateValue["db"] as! String,
                                      long: dateValue["long"] as! String,
                                      unix: dateValue["unix"] as! Int)

                self.dates.append(date)
            }
            print(self.dates)
            self.tableView.reloadData()
            break
        case .failure(_):
            print(response.result.error as Any)
            break

        }
    }
}

Then the only thing you need to do is to populate your tableView with the objects in the dates array:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dates.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let date = dates[indexPath.row]

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.textLabel.text = date.long
    return cell
}

Of course, it needs an adaptation according to your needs.

thxou
  • 691
  • 7
  • 20
1

Try this:

for (key, value) in data {
    guard let innerDict = value as? [String: Any] else {
        continue
    }

    print(innerDict["day"])

}

To store data you can create simple class with necessary fields and parse response in this class, then put all object into array, then to tableview.

class MyData : NSObject {
    var dateTitle: String?
    var day: Int?
    var date: Date?
    var month: Int?
    var quarter: Int?

    override init() {
        super.init()
    }
}

// ....

// in parsing function
var result = [MyData]()
    for (key, value) in data {
        guard let innerDict = value as? [String: Any] else {
            continue
        }
        let obj = MyData()
        obj.day = innerDict["day"] as? Int
        // etc...
        result.append(obj)

}

DispatchQueue.main.async {
    self.tableView.reloadData()
}
Eridana
  • 2,418
  • 23
  • 26
0

The value is itself a dictionary, so you could access individual fields like so

if let innerDict = value as? [String: Any] {
    print(\(innerDict["day"]))
    print(\(innerDict["db"]))
    ...
}
Dalton Sweeney
  • 1,108
  • 3
  • 11
  • 24
0

Declare string array

var arrjsondata = [String:Any]()

assign data in

arrjsondata = data

after reload your tableview

Jigar
  • 1,801
  • 1
  • 14
  • 29