Prevent browser cache from CSS, JS, and image files

In this article, I am going to teach you, how you can prevent the browser cache from keep displaying the old content. We will ask the browser to update your cached files and fetch the fresh content. Suppose, you have written a Javascript file named “script.js”. Now, you added some functionality code in that file, or change the algorithm of some function. You have updated the file on a live server. But your changes will not affect your user’s side if their browser has cached that JS file.

How browser cache works

In that case, you have to forcefully tell the browser to fetch the updated file instead of serving the cached file. The browser cache works in such a manner that, whenever a CSS, JS, or image file is rendered in the client’s browser, the browser stores the URL of that file in its cache along with its content. When the user refreshes the page, all <style>, <script> and <img /> tags request the resources using the “href” and “src” attribute. The browser checks if the requested URL already exists in its cache database. If “yes” then it (browser) fetches its content from the cache database and serves it.

That’s why most of the time your website users are not able to view the updated content. As you now know the problem, you now have a solution. The browser searches the URL in its cache database. So, whenever you update your file, simply change the URL by appending a query parameter at the end of the URL. For example, if you have an image tag which is displaying an image named “1.jpg”, like this:

<img src="1.jpg" />

Skip cache and fetch fresh content

Now, you have replaced the “1.jpg” image with a new image and you want the user’s to view the new image, then simply change the URL like this:

<img src="1.jpg?v=1" />

Here, “v” stands for “version” but you can use any parameter you want. Make sure to append it with “?” so it will be treated as a parameter. Its sole purpose is to tell the browser that the URL has now changed. So, it must fetch the updated resource instead of from the cache database. Now, every time you change the image file, simply increment this version value like “?v=2” and the image will be updated for all users next time they refresh the page.

If you want the browser to never cache a specific resource, for example, you want the web browser to always serve the updated “1.jpg” file. In that case, append the PHP timestamp in the query parameter. A PHP timestamp is the number of seconds passed from the 1st of January 1970 till the current time.

<img src="1.jpg?v=<?php echo time(); ?>" />

This will prevent the browser to never cache this image. Because every time user sends a request for this resource, the URL will change each time.

See this in action

Get URL query parameter value in Javascript

In this article, I am going to teach you, how you can get the URL query parameter value in Javascript. You can easily get the URL parameter in PHP using PHP’s built-in global $_GET array and pass the associative index as the name of the parameter. But getting that value in Javascript is a bit tricky. So I am going to show you a method that is very simple and will always work.

  1. Create a hidden input field.
  2. Give it a unique ID so it can be accessible in Javascript.
  3. Set its value as the variable you are receiving from the URL using the $_GET array.
  4. Array index will be the name of the parameter as in the URL

Suppose, you are receiving a parameter named “data” in your URL.

<input type="hidden" id="data" value="<?php echo $_GET['data']; ?>" />

Now, create a Javascript tag. You should execute all your Javascript code when the page is fully loaded. So, attach a “load” listener to the window object. You can also use the onload event but it will override the previous event. I have written a detailed post on the difference between onload event and “load” event listener.

window.addEventListener("load", function () {
    var data = document.getElementById("data").value;
    console.log(data);
});

The callback function in the second parameter of the addEventListener function will be called when the page is fully loaded. Now you simply need to get the value of this hidden input field using its ID and get the value attribute. I am logging the value of the data variable in the console.

Now, if you refresh the page then you will see this parameter (data) value in the console using Javascript. That’s how you can get the query parameter from the URL in your Javascript code.

WP Carousel slider plugin height issue [Fixed]

WP Carousel Slider is a WordPress plugin developed by Sayful Islam. This plugin allows you to create carousel images in your blog post. You can display your media images, gallery, custom URLs, blog posts, or WooCommerce products in the carousel.

It works as sliders, so you need to create a new slider, and add images to that slider. A shortcode will be generated for each slider, you just need to place that shortcode in your post where you want to show the slider. Sliders created from this plugin can also be used as widgets.

In this article, I am going to discuss a solution to a problem that occurs when you try to add images with different heights in your slider under the following configurations:

SettingValue
Carousel Image sizeOriginal uploaded image
Auto WidthDisabled
Columns1
Columns: Desktop1
Columns: Small desktop1
Columns: Tablet1
Columns: Small tablet1
Columns: Mobile1

If you are using the above settings and if you upload the images with different heights in a slider, then you might see that slider has been given a height of the largest image which will create a lot of empty space at the bottom of the smaller height images.

Moreover, when you scroll between carousel items, the height of the carousel is not auto-adjusted. Let me explain how you can solve this.

Solution:

You need to make 1 change in the plugin file. When it comes to editing the plugin files, there are 2 options.

1. WordPress admin panel

From your WordPress admin panel, go to “Plugins > Plugin Editor” and select the “Carousel Slider” plugin. When this plugin is selected, go to the following path:

assets/js/frontend.js

2. File manager

If you prefer to use file manager instead of making the changes from the WordPress admin panel, then you need to go to the following path:

wp-content/plugins/carousel-slider/assets/js/frontend.js

Replace the content of the “frontend.js” file with the following:

Before applying the solution, please prepare a backup of this file. Copy the content of this file and paste it into your computer’s Notepad.

If you have prepared the backup of this file, feel free to replace the file’s code with the following:

function setOwlStageHeight(event) {
    var maxHeight = 0;
    jQuery('.owl-item.active').each(function () { // LOOP THROUGH ACTIVE ITEMS
        var thisHeight = parseInt( jQuery(this).height() );
        maxHeight=(maxHeight>=thisHeight?maxHeight:thisHeight);
    });
    jQuery('.owl-carousel').css('height', maxHeight );
    jQuery('.owl-stage-outer').css('height', maxHeight ); // CORRECT DRAG-AREA SO BUTTONS ARE CLICKABLE
}

jQuery("body")
    .find(".carousel-slider")
    .each(function () {
        let a = jQuery(this),
            e = a.data("auto-width"),
            t = parseInt(a.data("stage-padding"));
        if (
            ((t = t > 0 ? t : 0),
            jQuery().owlCarousel &&
                (a.owlCarousel({
                    stagePadding: t,
                    nav: a.data("nav"),
                    dots: a.data("dots"),
                    margin: a.data("margin"),
                    loop: a.data("loop"),
                    autoplay: a.data("autoplay"),
                    autoplayTimeout: a.data("autoplay-timeout"),
                    autoplaySpeed: a.data("autoplay-speed"),
                    autoplayHoverPause: a.data("autoplay-hover-pause"),
                    slideBy: a.data("slide-by"),
                    lazyLoad: a.data("lazy-load"),
                    autoWidth: e,
                    navText: [
                        '<svg class="carousel-slider-nav-icon" viewBox="0 0 20 20"><path d="M14 5l-5 5 5 5-1 2-7-7 7-7z"></path></use></svg>',
                        '<svg class="carousel-slider-nav-icon" viewBox="0 0 20 20"><path d="M6 15l5-5-5-5 1-2 7 7-7 7z"></path></svg>',
                    ],
                    responsive: {
                        320: { items: a.data("colums-mobile") },
                        600: { items: a.data("colums-small-tablet") },
                        768: { items: a.data("colums-tablet") },
                        993: { items: a.data("colums-small-desktop") },
                        1200: { items: a.data("colums-desktop") },
                        1921: { items: a.data("colums") },
                    },
                    autoHeight: true,
                    onInitialized: setOwlStageHeight,
                    onResized: setOwlStageHeight,
                    onTranslated: setOwlStageHeight
                }),
                "hero-banner-slider" === a.data("slide-type")))
        ) {
            let e = a.data("animation");
            e.length &&
                (a.on("change.owl.carousel", function () {
                    a.find(".carousel-slider-hero__cell__content")
                        .removeClass("animated " + e)
                        .hide();
                }),
                a.on("changed.owl.carousel", function (t) {
                    setTimeout(function () {
                        jQuery(t.target)
                            .find(".carousel-slider-hero__cell__content")
                            .eq(t.item.index)
                            .show()
                            .addClass("animated " + e);
                    }, a.data("autoplay-speed"));
                }));
        }
        jQuery().magnificPopup &&
            ("product-carousel" === a.data("slide-type")
                ? jQuery(this).find(".magnific-popup").magnificPopup({ type: "ajax" })
                : "video-carousel" === a.data("slide-type")
                ? jQuery(this).find(".magnific-popup").magnificPopup({ type: "iframe" })
                : jQuery(this)
                      .find(".magnific-popup")
                      .magnificPopup({ type: "image", gallery: { enabled: !0 }, zoom: { enabled: !0, duration: 300, easing: "ease-in-out" } }));
    });

After replacing the above code, you need to refresh your browser cache in order to see the effect. Press the following keys to remove the browser cache:

Windows / Linuxctrl + shift + delete
Maccommand (⌘) + shift + delete

When you hit the above keys, you will see a pop-up asking which data you want to delete. You will have 3 options and you need to check the “Cached files and images” option. Also, make sure to select “All time” from the “Time range” option.

Now refresh the post where you have placed the shortcode for the WP Carousel Slider plugin, and you will know that the carousel will adjust itself dynamically with the height of the currently active image.

PayPal and Stripe – Javascript

Whether you are creating an E-commerce website or simply wanted to receive payments from your website using PayPal and Stripe, this script already contains all the source code you need to show Stripe and PayPal payment buttons and receive payments directly in your Stripe and PayPal accounts.

It also has a full shopping cart implementation, where you can add products to the cart, update quantities, remove products from the cart and move to checkout.

Demo

Home page

Here you can add products to the shopping cart and also you can remove products from the shopping cart.

When you add or remove a product from the shopping cart, you will see the shopping cart badge on top updating its values in real-time.

Shopping cart

On clicking the above “Cart” button you will be redirected to the shopping cart page where you can change the number of products and can also remove the product from the shopping cart.

You can also see the grand total at the bottom right that changes in real-time as you change the quantity of product or when you remove a product from the shopping cart.

Checkout

Here you can make the payment using Stripe or Paypal.

Fully documented code

Comments have been added with each line of code for explanation.

Separate file for each function

To manage the code, each payment method is separated in its own file. So you can easily change and modify the code as per your needs.

Convert POST request into AJAX, Javascript – Laravel

Suppose you have a form in your Laravel project that when submit sends the data to the server for processing. But when the form is submitted, your browser has to refresh the whole page which means that it needs to load all the CSS, JS, and image files again and also render all the HTML in the browser again. So you need to convert this POST request into an AJAX request to prevent the page from reloading.

I am using a form with a text field and an input type file so you can know how to send an image in an AJAX request.

<form method="POST" action="{{ url('/form-submit') }}" enctype="multipart/form-data" onsubmit="return onsubmitForm(this);">
    {{ csrf_field() }}

    <input type="text" name="name">
    <input type="file" name="file" accept="image/*">

    <input type="submit">
</form>

CSRF field is required in Laravel for POST requests. onsubmit event is attached to the form and it will call a Javascript function to send an AJAX request. Now we need to create that function in Javascript that will send an AJAX request to the server along with all the data in the form:

<script>
    // create function in Javascript
    function onsubmitForm(form) {

        // create AJAX instance
        var ajax = new XMLHttpRequest();

        // open the request
        ajax.open("POST", form.getAttribute("action"), true);

        // listen for response from server
        ajax.onreadystatechange = function () {
            // when the request is successfull
            if (this.readyState == 4 && this.status == 200) {
                // convert the JSON response into Javascript object
                var data = JSON.parse(this.responseText);

                // show the response
                alert(data.status + " - " + data.message);
            }

            // if the request fails
            if (this.status == 500) {
                alert(this.responseText);
            }
        };

        // create form data object
        var formData = new FormData(form);

        // send the request
        ajax.send(formData);

        // prevent the form from submitting
        return false;
    }
</script>

Comments have been added with each line for an explanation. Now we need to create a route in our web.php file inside the routes folder in Laravel 9.

use Illuminate\Http\Request;

Route::get('/', function () {
    return view('welcome');
});

// this is the route I will make it to return JSON data
Route::post("/form-submit", function (Request $request) {

    $request->validate([
        "name" => "required",
        "file" => "required|image"
    ]);

    DB::table("users")->insert([
        "name" => $request->name
    ]);

    $request->file("file")->storeAs("/public", $request->file("file")->getClientOriginalName());

    // return redirect()->back();

    // return the response in JSON
    return response()->json([
        "status" => "success",
        "message" => "Task has been done"
    ]);
});

First, we are validating that the request must have name and file fields and the file must be an image. Then we are inserting the data from the text field in the users table. You can find the sample database in the attachments below.

Then we are storing the image in a public/storage folder. You need to run the following command in order to make this work:

php artisan storage:link

Lastly, we are sending the response back in JSON format. That’s how you can convert a POST request into an AJAX request in Laravel.

[wpdm_package id=’951′]

Prevent form resubmission alert POST method – PHP

When you submit a form with a POST request and if you refresh that page, you will see an alert that says “Confirm form resubmission”. This is not good for the user experience. You cannot use the GET method because it will make the URL look bad. But we still need to prevent this form resubmission alert dialog.

So using this technique, you can achieve both. Submit the form without making the URL bad, and prevent the “form resubmission” alert.

Suppose you have a form with an input field that sends a POST request like the following:

<form method="POST" action="form-submit.php" onsubmit="return onFormSubmit(this);">
    <input type="text" name="name">
    <input type="submit">
</form>

Attach an event named “onsubmit” to the form tag that calls a Javascript function named “onFormSubmit”. The return statement is used to prevent the form from submitting. Now, create that function in Javascript:

<script>
    function onFormSubmit(form) {

        // create data object with all form values
        var data = {
            "name": form.name.value
        };

        // convert in JSON
        var jsonData = JSON.stringify(data);

        // save in cookies
        document.cookie = "my_form=" + jsonData;

        // redirect to form's action
        window.location.href = form.getAttribute("action");

        // prevent form from submitting
        return false;
    }
</script>

Comments have been added with each line for an explanation. You can write all your form fields in the data object. If you have an input type=”file” field in your form, you can add it to the data object by calling the files property like the following:

var data = {
    "image": form.image.files[0]
};

For multiple files, you can simply remove the [0] from the above line and it will add all files in the data object.

Now on server-side, do the following to get the values:

<?php

    // get in server side
    $my_form = $_COOKIE["my_form"];

    // decode from JSON
    $my_form = json_decode($my_form);

    // get single value
    $name = $my_form->name;

    print_r($name);
?>

As we were storing the values in cookies using Javascript, so we can get them from cookies using PHP.

As we were storing the values in JSON string using Javascript. So, we can get them by decoding from JSON string using PHP.

That’s how you can prevent the “form resubmission” alert and also keep your URL clean from GET request.

[wpdm_package id=’949′]

Posted in PHP

Custom sort associative array – PHP

Suppose you have an associative array in PHP with key-value pair. If you loop through it, all the values will be displayed in the order they are added to the array. To learn how to customize the sorting of an associative array, keep reading this. We will teach you how you can custom sort an associative array in PHP. You can easily sort the numeric key though.

We will use a database called “classicmodels”, which can be found in the source files attached below. First, we will connect with the database and get all the columns of the desired table.

<?php

    $conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels");
    $result = mysqli_query($conn, "SELECT * FROM customers");

    $columns = [];
    while ($row = mysqli_fetch_object($result))
    {
        foreach ($row as $col_name => $col_value)
        {
            array_push($columns, $col_name);
        }
        break;
    }
    mysqli_data_seek($result, 0);

If you do print_r($columns); after this, then you will see all the column names of that table. Now create an array that holds the desired sorting of columns.

$columns_order = [
    "customerNumber" => "ID",
    "customerName" => "Name",
    "salesRepEmployeeNumber" => "Sales rep Employee ID",
    "contactFirstName" => "Contact peron name",
    "phone" => "Mobile",
    "addressLine1" => "Address line 1",
    "addressLine2" => "Address line 2",
    "city" => "City",
    "state" => "State",
    "postalCode" => "Zip code",
    "country" => "Country",
    "creditLimit" => "Credit limit"
];

The key of each element is the name of the column in the database. And the value is the text that will be shown against that column. Now comes the most important part, to display the first table row which is usually the heading, do a foreach loop on this array and display the value in TH:

<table>
    <tr>
        <?php foreach ($columns_order as $key => $value): ?>
            <th>
                <?php echo $value; ?>
            </th>
        <?php endforeach; ?>
    </tr>
</table>

To display the data as in new order, loop through each record in the database. Then run a nested foreach loop like above, and show the values based on the key of an associative array:

<?php while ($row = mysqli_fetch_object($result)): ?>
    <tr>
        <?php foreach ($columns_order as $key => $value): ?>
            <td>
                <?php echo $row->{$key}; ?>
            </td>
        <?php endforeach; ?>
    </tr>
<?php endwhile; ?>

Try changing the order of columns from $columns_order array. You can also try deleting columns from this array, so if you want to remove some columns from the table tag, you can simply remove that from $columns_order array.

That’s how you can custom sort an associative array in PHP. Learn how to custom sort data from MySQL database following this tutorial.

[wpdm_package id=’942′]

How to view error from AJAX, Javascript – Laravel

When you are calling an AJAX in Laravel, you will see a “500 – Internal Server Error” if there is an error in your PHP code. To see the actual error, kindly follow this article. We will teach you in this tutorial, how you can view error from your AJAX request.

Suppose I am calling an AJAX request in Laravel using core Javascript (no jQuery), then your code will be like this:

Javascript AJAX

var ajax = new XMLHttpRequest();
ajax.open("POST", document.getElementById("base-url").value + "/ajax-test", true);

ajax.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText);
    }

    if (this.status == 500) {
        console.log(this.responseText);
    }
};

var formData = new FormData();
formData.append("_token", document.querySelector("meta[name=_token]").content);
ajax.send(formData);

Line #1: I have created an AJAX object.

Line #2: I have opened the AJAX request with the POST method and the URL where the request will be sent. The third parameter (true, false) is the asynchronous boolean.

Note: All modern browsers recommend this value to be true.

Line #4: An event listener that will be called each time the status of request is changed.

#5: Check if the request is successful and the response has been received from server.

#6: Display the response from the server in browser console.

#9: Check if there is an internal server error. If yes, then display that error in line #10.

#14: New form data object is created that will send the data with an AJAX request.

#15: A CSRF (cross-side request forgery) token is appended in the form data object. We will create that meta tag later in this article.

Note: Every POST request in Laravel requires a CSRF token to be sent along with request.

Line #16: Sending the AJAX request along with form data object values.

You can create the hidden base URL and CSRF token tags as follows:

<input type="hidden" id="base-url" value="{{ url('/') }}">
<meta name="_token" content="{{ csrf_token() }}">

Now, whatever the error you are having on your server-side, in route, or in the controller, you will see that in your browser console window.

jQuery AJAX

If you are using jQuery to send an AJAX request and not seeing the actual error from your server-side, then change your jQuery AJAX function to the following:

$.ajax({
    url: document.getElementById("base-url").value + "/ajax-test",
    method: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function (response) {
        console.log(response);
    },
    error: function (xhr) {
        console.log(xhr.responseText);
    }
});

Now, if you have an error in your AJAX request, you can view it in the “error” callback. Learn how to convert a simple POST request into an AJAX request following this tutorial.

[wpdm_package id=’938′]

Show API data in XCode preview – Swift UI

You won’t be able to preview your layout in your XCode preview in Swift UI when you are receiving data from the server. So we are going to show you how you can preview the layout with the data from your API.

Video tutorial:

API to return JSON data

First, create an API that will return the JSON in a pretty format. We are going to create that API in PHP. You can find the sample database in the attachment below.

<?php

    $conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels");

    $result = mysqli_query($conn, "SELECT * FROM customers");

    $data = array();
    while ($row = mysqli_fetch_object($result))
    {
        array_push($data, $row);
    }

    header("Content-Type: application/json");

    echo json_encode($data, JSON_PRETTY_PRINT);

?>

It does the following things:

  1. Connect with the database.
  2. Fetch records from the customer’s table.
  3. Create a new empty array.
  4. Loop through all records from the database.
  5. Push in the array.
  6. Return the response as JSON pretty format.

If you run this file in your browser using XAMPP, WAMP, or MAMP, you will see all the data in JSON format. Copy all the content from the browser.

Create a JSON file in the XCode project

Now create a new file in your XCode project named “data.json”, you must select “Empty” while creating a new file in your XCode project. And paste the copied content into that file.

Create model class

Now in your View where you want to show the data, first create a model class that will hold the values you want to show in your List view.

// ResponseModel.swift

class ResponseModel: Codable, Identifiable {
    var customerName: String? = ""
    var country: String? = ""
}

Model class must implement Codable and Identifiable protocols.

Create an array of models

Inside your View class, create an array of these models and initialize it as an empty array.

@State var models: [ResponseModel] = []

List view

Now create a List view and show these 2 variables from the model class in the Text view.

VStack {
    List (models) { (model) in
        Text(model.customerName ?? "").bold()
        Text(model.country ?? "")
    }
}

This is the syntax to create a list view from an array. We are making the customer name to bold so we can differentiate between the customer name and country.

The layout could be different as per your need.

Read JSON file and Decode it into the model

Now we need to fill this “models” array with data from the JSON file we saved in our project. Following is the code that will read the JSON file from the XCode project and decode the JSON data into an array of models.

guard let url: URL = Bundle.main.url(forResource: "data", withExtension: "json") else {
    print("data.json not found")
    return
}

do {
    
    let data: Data = try Data(contentsOf: url)
    
    self.models = try JSONDecoder().decode([ResponseModel].self, from: data)
    
} catch {
    print(error.localizedDescription)
}

It does the following:

  1. Get the file from the bundle named “data.json”. The guard statement will throw an error if the file is not found. The bundle will return a URL object.
  2. Create a do-catch block that will throw an error if the data is not decodable to ResponseModel class.
  3. Convert the URL into a Data object.
  4. Decode the Data object into an array of ResponseModel class and assign it to the “models” array.

As “models” is a @State variable so it will automatically render the List view when the data is added to the model’s array.

Render List view

You can run the above inside your VStack’s onAppear function like below:

VStack {
    List (models) { (model) in
        Text(model.customerName ?? "").bold()
        Text(model.country ?? "")
    }
}.onAppear(perform: {

    // above code here

});

Conclusion

This is really helpful because when you are developing an app, you have to preview the layout you are designing in XCode, instead of re-running the app again and again to see the output.

You can do this with every API whose data you want to show in your Swift UI app. So that’s how you can show your API data in your XCode preview.

Learn how to create a search bar with history in Swift UI and SQLite.

Search bar Swift UI with history – SQLite

[wpdm_package id=’866′]

Get data from API and show in list – Swift UI, PHP

We will create a simple iOS app in Swift UI that will call an API request, developed in PHP, to the HTTP server. The API will return an array of records in JSON format, which we will decode in Swift class objects as an array. Then we will display that list in a list view.

If you prefer a video tutorial:

Our API will be in PHP and we will call it from our Swift UI app. So, create a file in your htdocs (for XAMPP), or www (for MAMP or WAMP) folder and paste the following code in it. We have created a folder named “test” and inside it, the file name is “swiftui-get-data-from-api.php”:

<?php

    $conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels");

    // get data from database
    $result = mysqli_query($conn, "SELECT * FROM customers");

    // adding in array
    $data = array();
    while ($row = mysqli_fetch_object($result))
    {
        array_push($data, $row);
    }

    // send as response
    echo json_encode($data);

?>

For that, you need to create a database named “classicmodels” in your phpMyAdmin and import the SQL file attached below. You need to create and login into your account in order to download that file. You can see the output from the link:

http://localhost/test/swiftui-get-data-from-api.php

This might be changed and it depends on the path of your file. You will see a lot of data, for example, we want to show only customerName and country in our Swift UI app. So you need to create a model file in your project using XCode and paste the following code into it:

// ResponseModel.swift
class ResponseModel: Codable, Identifiable {
    var customerName: String? = ""
    var country: String? = ""
}

Now in your View file where you want to show the list, you can paste the following code:

@State var models: [ResponseModel] = []
    
var body: some View {
    // Create VStack
    VStack {
        // now show in list
        // to show in list, model class must be identifiable
        
        List (self.models) { (model) in
            HStack {
                // they are optional
                Text(model.customerName ?? "").bold()
                Text(model.country ?? "")
            }
        }
        
    }.onAppear(perform: {
        // send request to server
        
        guard let url: URL = URL(string: "http://localhost:8888/test/swiftui-get-data-from-api.php") else {
            print("invalid URL")
            return
        }
        
        var urlRequest: URLRequest = URLRequest(url: url)
        urlRequest.httpMethod = "GET"
        URLSession.shared.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
            // check if response is okay
            
            guard let data = data else {
                print("invalid response")
                return
            }
            
            // convert JSON response into class model as an array
            do {
                self.models = try JSONDecoder().decode([ResponseModel].self, from: data)
            } catch {
                print(error.localizedDescription)
            }
            
        }).resume()
    })
}

All the code is self-explanatory and comments are also added to explain difficult lines. But if you still face any issues in following this tutorial, please let us know.

[wpdm_package id=’847′]