Retrieving information from dictionary in swift version 4

Currently, I am utilizing an API and trying to display its data in a 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()
    }

    // Additional code for API implementation, data retrieval, and segmented control handling 

}

class TableCell: UITableViewCell {

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

}

Following this code, I have managed to extract keys and values; however, there seems to be an issue where 6 values are being retrieved under 1 key. How can I effectively store and display all these values within the table view? My approach involves using a segmented controller to dynamically alter the displayed data based on date months, as shown in the image https://i.stack.imgur.com/moqnx.png.

Answer №1

To begin, you can define a custom class to represent the response:

class DateInfo: NSObject {
    var quarter: Int!
    var day: String!
    var month: String!
    var db: String!
    var longDate: String!
    var unixTime: Int!

    init(quarter: Int, day: String, month: String, db: String, longDate: String, unixTime: Int) {
        super.init()

        self.quarter = quarter
        self.day = day
        self.month = month
        self.db = db
        self.longDate= longDate
        self.unixTime = unixTime
    }
}

Next, create an array to hold all the retrieved dates:

var dateList = [DateInfo]()

Update your fetchData method like this:

func fetchData() {
    Alamofire.request("https://api.example.com/get-dates", 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["dates"] as? [String: Any] else { return }

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

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

        }
    }
}

Finally, populate your tableView with the items from the dateList array:

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

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

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

Remember to adjust it based on your specific requirements.

Answer №2

Check out this code snippet:

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

    print(innerDict["day"])

}

If you want to store the data, consider creating a simple class with necessary fields and parsing the response into that class. Then, add all objects into an array and display them in a table view.

class UserData : NSObject {
    var title: String?
    var day: Int?
    var date: Date?
    var month: Int?
    var quarter: Int?

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

// ....

// Parsing function
var userDataArray = [UserData]()
for (key, value) in data {
    guard let innerDict = value as? [String: Any] else {
        continue
    }
    let userObj = UserData()
    userObj.day = innerDict["day"] as? Int
    // Parse other fields here...
    userDataArray.append(userObj)

}

DispatchQueue.main.async {
    self.tableView.reloadData()
}

Answer №3

Contained within this entity is a dictionary structure, allowing for access to specific elements in the following manner

if let subDict = value as? [String: Any] {
    print(\(subDict["day"]))
    print(\(subDict["db"]))
    ...
}

Answer №4

Create a new string array

let jsonData = [String:Any]()

Store some data in it

jsonData = data

Then refresh your tableview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting a generic JSON object to a Map interface using GSON

Considering the given JSON object below: { "id": 5, "data: { ... } } Could it be successfully transformed into the following POJO? class MyEntity { int id; Map<String, Object> data; } I am looking to maintain an open-ended structure ...

Imitation Services JSON

How can I easily create mock json services? Are there any tools available similar to those for soap? Thank you ...

The web service fails to process the substantial request

My issue involves an asp.net web service where I send my data to a database. The data is being encoded using the encodeURI function before sending it through a text editor (ckeditor). The problem arises when I try to transmit more than approximately 1200 c ...

Display the JSON result from a RESTful API call within an Ionic framework

I am facing a challenge in displaying a JSON response retrieved from a RESTful API request. Below is the code snippet: products:Observable<any>; constructor(public navCtrl: NavController, private backgroundGeolocation: BackgroundGeolocation, public ...

Verifying the content of the JSON data

If I receive JSON data that looks like this: {"d":1} Is it possible to determine whether the value after "d": is a 1 or a 0? I attempted the following method, but it always goes to the else block, even though I know the JSON data contains a 1. success: ...

An issue has arisen while parsing a JSON array that is set up to accept

My code works perfectly fine when I provide a single data element in my JSON file. However, when I input an array of elements, it starts displaying "undefined" on the client side. Below is the snippet of my server-side code: var app = require('expres ...

The jQuery ajax call is returning some undefined results, which is in contrast to the network response, which appears to be completely accurate

My system utilizes an oracle-db and a php-script that is triggered by a query ajax-call. Here is the php-script: $query = 'SELECT pl.event_id, pl.og2, d.name dst, pl.state, pl.note, pl.createdate FROM publevels pl LEFT JOIN dst d on (d.og2 = pl.og ...

JavaScript library called "Error: JSON input ended unexpectedly"

I am currently operating a server using node.js and Express v4.0 Additionally, I am utilizing the request library. However, when receiving a response from the server, I encounter an Uncaught SyntaxError: Unexpected end of JSON input. The response I receiv ...

Convert Ruby array into a hash using specific parameters

Here is an array I have: fruits = ["apple", "banana", "orange"] My goal is to convert it into a JSON format like this: '{"apple": {}, "banana": {}, "orange": {} }' I specifically want to avoid this format: '{"apple"=> {}, "banana"=& ...

retrieve the value of a specific key using JSON stringify

[{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayo ...

There seems to be an issue with Ajax functionality within the Webix framework

Exploring webix for the first time has been quite an interesting journey. I am carefully following the guidance provided in the getting started document to create my own webix program. By placing my code in an HTML page and two JSON files as instructed, he ...

Reading Json Files with Pandas - Dealing with Extra Trailing Data

I'm currently facing an issue while attempting to read a large Json file using Pandas' pd.read_json function. An error message keeps popping up, specifically: ValueError: Trailing data. Despite conducting extensive research on this matter, I hav ...

Navigating the intricacies of HTTP PATCH: Working with arrays, removing items, and creating nested

Seeking guidance on effectively implementing the PATCH verb for making partial updates to a noun within a RESTful API using JSON. While we understand that PATCH is intended for partial updates, there is still a lack of standardization surrounding the synta ...

The correct method for creating an external JSON file

As I browse through numerous JSON tutorials online, including those on STO, I find myself in a state of confusion when it comes to determining the right approach for writing an external JSON file. I have come across various examples such as: (although Ad ...

How can we minimize the data contained in JSON HTML markup?

https://i.stack.imgur.com/mzuB0.png Currently, I am attempting to find a way to conceal the last 12 digits in the price shown on a button, as it is excessively long. The method I am utilizing involves a JSON api and insertAdjacentHTML markup. This snipp ...

Python: Exceeding the maximum recursion depth error occurred when calling a Python object

Today, while working on my code, I encountered an error that I cannot seem to figure out. I am not sure what is causing it. The error message: Traceback (most recent call last): File "D:/Drive/Outros/Python/Projects/Simple_Dict_bot.py", line 63, in loo ...

What is the best way to retrieve text from the p tag and input it into the text field?

Looking to resolve a situation where two identical IDs exist and need to implement some JQuery. The objective is for the input value to automatically update itself based on changes in the text of the p tag. $(document).ready(function(){ ...

Ways to delete a blank key from a MySQL json field

I need to modify a MySQL table with a json field that contains an empty key. I am looking for a way to remove this empty key from the JSON field. Current data: update t1 set info = REPLACE(info, '"": "",', ''); The ...

Jquery not populating table as anticipated

I am having an issue with populating a table using a JSON file. The first row works fine, but the subsequent rows are not showing up. Can someone please help me identify what I am doing incorrectly? Is my looping structure flawed? Thank you for your assi ...

The JSON data fails to load upon the initial page load

I am having trouble getting JSON data to display in JavaScript. Currently, the data only shows up after I refresh the page. Below is the code I am using: $(document).ready(function () { $.ajax({ url:"http://192.168.0.105/stratagic-json/pr ...