The initial button click does not display data

I am currently facing an issue with my app when trying to display JSON data retrieved from a PHP web service. The problem occurs when I click the fetch button for the first time and the data does not show up on the labels.

After debugging, I noticed that the data is successfully passed to the array but it fails to populate the labels in the view controller.

Can anyone provide assistance with resolving this issue?

Thank you in advance.

Button click

@IBAction func btn_ler(_ sender: Any)
    {
        
        //txt_matricula.text = ""
        //txt_marca.text = ""
        //txt_modelo.text = ""
        
        retrieve_vehicle_data(licensePlate: input_licensePlate.text!)
        
        for vehicle in all_vehicles
        {
            txt_matricula.text = vehicle.LICENSE_PLATE
            txt_modelo.text = vehicle.MODEL
            txt_marca.text = vehicle.BRAND
        }
        
        //lbl_num_servicos.text = String( all_vehicles.count)
    }

Function to retrieve the JSON

func retrieve_vehicle_data (licensePlate : String)
    {
        //Variable containing the URL
        let v_url = "URL"
        
        let o_url = URL(string: v_url)
        
        URLSession.shared.dataTask(with: o_url!)
        {
            (data, response, error) in
            
            do
            {
                let vehiclesData = try JSONDecoder().decode([Vehicle].self, from: data!)
                

                //for vehicleData in vehiclesData
                //{
                    //print(vehicleData.LICENSE_PLATE)
                all_vehicles = []
                    all_vehicles.append(contentsOf: vehiclesData)
                //}
            }
            catch
            {
                print("We have an error!")
                //self.txt_matricula.text = "We have an error!"
            }
            print( all_vehicles.count)
            }.resume()
    }

Answer №1

To successfully retrieve data, ensure you include a completion closure in your obter_dados_veiculo method as shown below:

func obter_dados_veiculo (matricula : String, completion:@escaping(Bool,Error?)->())
{
    //Variable to store the URL
    let v_url = "URL"
    
    let o_url = URL(string: v_url)
    
    URLSession.shared.dataTask(with: o_url!)
    {
        (data, response, error) in
        
        do
        {
            let matriculas = try JSONDecoder().decode([s_veiculo].self, from: data!)
            
            
            //for matricula in matriculas
            //{
            //print(matricula.MATRICULA)
            a_veiculos = []
            a_veiculos.append(contentsOf: matriculas)
            completion(true,nil)
            //}
        }
        catch let error as NSError
        {
            print("We have an error!")
            completion(false,error)
            //self.txt_matricula.text = "We have an error!"
        }
        print( a_veiculos.count)
        }.resume()
}

Then, make the following call:

@IBAction func btn_ler(_ sender: Any)
{
    
    //txt_matricula.text = ""
    //txt_marca.text = ""
    //txt_modelo.text = ""
    
    obter_dados_veiculo(matricula: input_matricula.text!) { (success, error) in
        for veiculo in self.a_veiculos
        {
            txt_matricula.text = veiculo.MATRICULA
            txt_modelo.text = veiculo.MODELO
            txt_marca.text = veiculo.MARCA
        }
    }
    
    //lbl_num_servicos.text = String( a_veiculos.count)
}

Answer №2

The issue you are facing stems from the fact that you are making asynchronous network requests, which means there is no guarantee that the response will be received before you try to assign text to labels.

    retrieve_vehicle_data(licensePlate: input_licensePlate.text!)

    //RESPONSE MAY NOT BE RECEIVED

    for vehicle in a_vehicles
    {
        txt_licensePlate.text = vehicle.LICENSE_PLATE
        txt_model.text = vehicle.MODEL
        txt_brand.text = vehicle.BRAND
    }

One approach you can take is to use property observers on a_vehicles, like this:

var a_vehicles: [s_vehicle] = [] {
    didSet {
        for vehicle in a_vehicles
          {
             txt_licensePlate.text = vehicle.LICENSE_PLATE
             txt_model.text = vehicle.MODEL
             txt_brand.text = vehicle.BRAND
          }
    }
}

Answer №3

Include a method called initData() in your code.

 func initData() {
   for vehicle in vehicleArray
    {
        licensePlate.text = vehicle.LICENSE_PLATE
        model.text = vehicle.MODEL
        brand.text = vehicle.BRAND
    }

 }

Make sure to call this method when initializing your array.

 func get_vehicle_data (license_plate : String)
     {
    //Variable holding the URL
    let url = "URL"

    let urlString = URL(string: url)

    URLSession.shared.dataTask(with: urlString!)
    {
        (data, response, error) in

        do
        {
            let vehicles = try JSONDecoder().decode([Vehicle].self, from: data!)


            //for vehicle in vehicles
            //{
                //print(vehicle.LICENSE_PLATE)
            vehicleArray = []
                vehicleArray.append(contentsOf: vehicles)
          initData()
            //}
        }
        catch
        {
            print("We have an error!")
            //self.licensePlate.text = "We have an error!"
        }
        print( vehicleArray.count)
        }.resume()
}

Answer №4

Implement a completion handler to receive updates once your API call is complete and update the UI accordingly. Here's an example of how you can utilize a completion handler:

@IBAction func btn_ler(_ sender: Any)
{
    
    get_vehicle_data(licensePlate: input_licensePlate.text!) {
        DispatchQueue.main.async {
            for vehicle in vehicles
            {
                txt_licensePlate.text = vehicle.LICENSE_PLATE
                txt_model.text = vehicle.MODEL
                txt_brand.text = vehicle.BRAND
            }
        }
    }
}

func get_vehicle_data (licensePlate : String, completionHandler: @escaping () -> Void) {
    //Variable holding the URL
    let url = "URL"
    let requestUrl = URL(string: url)
    URLSession.shared.dataTask(with: requestUrl!) {
        (data, response, error) in
        do {
            let plates = try JSONDecoder().decode([vehicle_details].self, from: data!)
            vehicles = []
            vehicles.append(contentsOf: plates)
        }
        catch {
            print("We have an error!")
            //self.txt_licensePlate.text = "We have an error!"
        }
        print(vehicles.count)
        }.resume()
}

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

How can labels be added when mapping over JSON data?

If I have JSON data structured like this: { "siteCode": "S01", "modelCode": "M001", "modelDesc": "Desc01", "price": 100 "status": "A", "startDate": "Ma ...

Utilizing the docker-compose JSON logging driver with custom environment labels

My goal is to retrieve logs in the following format: {"log":"Using CATALINA_BASE: /opt/apache-tomcat-7.0.76\r\n","stream":"stdout","time":"2017-04-19T04:28:33.608418994Z","attrs":{"production_status":"testing","os":"ubuntu"}} I have set up my ...

Retrieving a single value from the response entity JSON data

I am in need of connecting to a rest service in order to retrieve the user id using a token. List<Object> providers = new ArrayList<>(); providers.add(new JacksonJaxbJsonProvider()); client = WebClient.create(properties.getProperty(URL), prov ...

The type hint feature in JSON4S is not functioning as expected

Here is a code snippet that has been causing an issue: implicit val formats = DefaultFormats + FullTypeHints(Contacts.classList) val serialized = Serialization.write(List(Mail(field = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

gson: customized fromJson method based on the data type

Apologies if this has been asked before, but I couldn't find the information I'm looking for. Here are the different message types I have: class AbstractMessage { int code; String token; } class ShareMessage extends AbstractMessage{ ...

Creating dropdown options with JSON and Angular

This dilemma has been causing me no end of distress. I am trying to figure out how to populate options for a select tag from a JSON object using Angular. Here is a snippet of the code: <select id="cargo" ng-model="cargo.values.cargoList"> <op ...

Using getJSON to return key/value pair from local host URL in JSFiddle - A step-by-step guide

After following a tutorial on building an API using Python, Flask, SQLite, and SQLAlchemy, I have successfully tested the connection by hitting the localhost address in my browser. Now, I am curious if it is possible to test this connection and see the des ...

What is the best way to combine these two arrays in order to generate the desired JSON structure in a React

Is there a way to transform two arrays like these: const age = [31,53,62] const names = ['john', 'sam', 'kathy'] Into the structure shown below: const data = { "children": [ { "id": 1, "name": "john", "age ...

Converting JSON arrays into Python lists

I am encountering difficulties in parsing a JSON array I created into a Python list. Despite my efforts, I have not been successful in achieving this. Is there a way to convert my JSON array into a Python list? The structure of the json data I want to pa ...

Retrieving JSON data from PHP using jQuery

I've been struggling with this issue for two whole days now, and I feel like I've hit a dead end in trying to solve it on my own. Here's the situation: I have two pages - one that contains a form with an address field that gets auto-filled ...

Issues detected with the callback function of jQuery validation engine

I am currently utilizing the jQuery ValidationEngine plugin to validate a form. The validation itself is working fine, however upon completion, instead of redirecting to the previous page as expected, a JSON string is displayed on the screen. Below is the ...

The attempt to fetch the submitted data via the PHP URL was unsuccessful

I have a form and I've created a URL to fetch data. The data is being fetched properly, but when I try to access the URL, it shows {"error":"null"}. How can I retrieve the submitted value? I am having trouble displaying the web services as I attempt t ...

The file reading code in my Node.js application suddenly stopped working

I have a basic web application that I am currently developing using Node.js and Express. This is a breakdown of my package structure: https://i.stack.imgur.com/D7hJx.png The entries in my questions.json file are outlined below: [ { "question": "Wh ...

Storing a collection of integers within a nested data structure

Our team has implemented a custom serializer in C# to convert objects into JSON format for interacting with a REST API. The API requires data to be formatted like this: "product": { "sku": "211554", "extras": [{ "code": ...

An error occurred when trying to pass JSON data to the view in the "orchard" framework: TypeError - e.slice is not a function

public ActionResult Grouping() { return View(); } public ActionResult Read([DataSourceRequest] DataSourceRequest request, string text) { var result = _auto.Table.ToList().Where(s => s. ...

Using Guzzle to Make a JSON POST Request in Laravel 5.7

I need help with my code. I am trying to create a new store in Geoserver. public function post_store(String $name) { $client = new Client(); $res = $client->request('POST', 'http://localhost:8080/geoserver/rest/workspaces/&a ...

Generate a new tree structure using the identifiers of list items within an unorganized list

Attempting to convert the id's of li's in a nested unordered list into valid JSON. For example, consider the following list. To be clear, the goal is not to create the UL list itself, but rather the JSON from the li id's <ul class="lis ...

Using a PHP if statement within a CSS class

While attempting to send a JSON response from my Laravel controller, I encountered an issue with using an if statement within the class. Surprisingly, no errors were thrown but nothing seemed to work as expected. This is the snippet of code I tried: fore ...

What is the best way to update JSON data using JQuery?

I apologize for posing a seemingly simple query, but my understanding of JavaScript and JQuery is still in its early stages. The predicament I currently face involves retrieving JSON data from an external server where the information undergoes frequent ch ...

Trouble integrating JSON data with Newtonsoft.Json library in WPF applications

Currently, I am working on extracting data from the office365 API that returns responses in JSON format. My aim is to store specific data such as Id and DisplayName into variables for further use, but I seem to be struggling with the process. I came across ...