Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Develop an E-Commerce iOS Application in 24 Hours

DZone's Guide to

Develop an E-Commerce iOS Application in 24 Hours

In this tutorial, you'll learn how to create the different components of a basic e-commerce application for iOS using XCode and Swift.

· Mobile Zone ·
Free Resource

In my previous tutorials, I have explained more than once how to create a new application using XCode and Swift and implement some components. Using the knowledge from the previous tutorials, we’ll try to implement a basic e-commerce application.

Required previous knowledge:

We’ll start by defining requirements for this application and how each of them can be implemented, plus which components, navigation, and frameworks we’ll use.

Requirements:

  • Navigation

  • Products listing

  • Product details

  • News

  • About

  • Terms and conditions

In this tutorial, we’ll show the whole concept behind one basic e-commerce application and how some of the logic is implemented, plus some of the screens; the rest of the screens, like News View Controller (which is  similarly implemented like Home View Controller), About, and Terms will be left for the user to implement, like in this example from GitHub.

Navigation

There are different navigational patterns which can be used, like side menu, tab-based, dashboard, or mixing two navigation patterns for much more complex solutions, for some of them how can be implemented please check my previous tutorials. For our e-commerce application, we will use tab bar navigation with 4 tabs for main view controllers and navigation controller for accessing view controllers not accessible from the tab bar navigation. The first tab will display the list of products; the second tab is reserved for displaying news like events and discounts; in the third tab, we’ll display some short info for us; and in the fourth tab are the terms and conditions. 

Home

The second decision is how to display the list of products in our application. We’ll display the products in a grid with two products per row using the UICollectionView component.

Home products grid

Next, we need to design a custom cell that will fit in our concept. First, we need to decide what we will display in this cell, which is the relevant product information we want to display to the customer and how the cell will look. For the simplest cell, we need the main product image, product name, and product price. The main image will occupy the whole cell background, and at the top of the cell, we will put another view where we will display the product name and the product price. If the customer touches some of the listed products, we’ll display a product details view.

Products cell

The logic behind this Home View Controller is to load all products (or load for a specific category) from the API and display it in UICollectionView. While loading the products from the API, we’ll display one progress bar which is the default functionality to inform the customer that the application is working. Loaded products will be stored globally for easy access from different view controllers. Because the complete product data will be stored in an object, we can easily send that product object in Product Details View Controller to display all details when the customer chooses some product from the Home View Controller. If we have a menu for listing categories, we can load the products for the selected category from the API and overwrite the global saved product objects. In our example, we have in the top right corner a button for displaying a categories menu.

Basically, we have finished with the product listing, so next, we will design the mockup for product details.

Product Details

The product details view will show the complete product details, including product name and product price. For navigation between Home view where the products are listed in UICollectionView component and Product Details, we are using UINavigationController for navigation which give us option Home tab to have separate navigation stack from UITabBar component where UITabBar component have own navigation stack with predefined views controllers for each tab.

Product Details

At the top of the view we’ll have one view where the product name and product price are displayed as labels, right after this view we will place UIImageView and after the image view where the product image will be displayed, we will place one UITextView for product details. At the bottom of the image in the right corner, we will put two buttons vertical positioned, where the blue one will trigger share functionality and the red one will trigger sending mail form to the to the predefined email address. Product Details View Controller will display selected product object from the previous view controller – Home View Controller.

This next image shows the application Storyboard with all view controllers designed and connected.

Image title

Implementation

The first thing what we should do is create a new pod file and save the configuration from below into the newly created pod file, and in the terminal, run the command $ pod install . 

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'CustomShop' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!
  # Pods for CustomShop
pod 'Alamofire', '~> 4.2'
pod 'SVProgressHUD', '~> 2.0'
pod 'PMJSON', '~> 2.0'
pod 'UIColor_Hex_Swift', '~> 3.0.2'
pod 'TPKeyboardAvoiding', '~> 1.3'
pod 'SDWebImage', '~> 3.8'
pod 'DPDropDownMenu'
pod 'GTToast'

end


We will use the Alamofire framework for network communication, SVProgressHUD for the animated progress bar while loading data from the API, PMJSON for easy JSON processing, SDWebImage for image loading and caching, GTToast for displaying short animated messages, DPDropDownMenu for the categories menu, TPKeyboardAvoiding in case we need to implement a form with multiple text fields, and UIColor_Hex.

The next image shows the application project structure.

Project structure

As I mentioned earlier, most of the code is easy to implement by following my previous tutorials. In this tutorial, I will show the most interesting part of the application, which is network communication and object serialization. A good practice is to implement a layered application structure where we’ll have all network operations as a separate network layer in the application, so later, we can make better abstraction using a different type of connectivity and data aggregation from the API.

Our API client is a singleton and is using Alamofire and PMJSON frameworks.

ApiClient.swift

import UIKit

import Alamofire

import PMJSON

class ApiClient: NSObject {
    static let sharedInstance:ApiClient = ApiClient()

    let BASE_URL = "http://localhost:8080"

    let API_LIST_NEWS = "/list_news"
    let API_LIST_PRODUCTS = "/view_customer_products"

    func findProductsByCategory(categoryName:String, completition:@escaping (Bool, [ProductEntity]) -> ()) {
        let apiParams:[String:String] = ["random_products":"1", "page":"1"]

        Alamofire.request(BASE_URL+""+API_LIST_PRODUCTS, method: .post, parameters:apiParams).responseString(completionHandler: { (response) in

            let stringResponse = response.result.value!

            var jsonData:JSON

            do
            {
                jsonData = try JSON.decode(stringResponse)

                let resultArray = try jsonData.getArray("data")

                    if resultArray != nil {

                        var productsArray:[ProductEntity] = [ProductEntity]()

                        for i in 0 ..< (resultArray.count) {
                            let productDataObj = resultArray[i]

                            let productEntity:ProductEntity = ProductEntity()

                            productEntity.productID = try productDataObj.getString("id")
                            productEntity.productCategory = try productDataObj.getString("cat_name")
                            productEntity.productName = try productDataObj.getString("product_name")
                            productEntity.productDescription = try productDataObj.getString("description")
                            productEntity.productPrice = try productDataObj.getString("output_price")
                            productEntity.productMedia = try productDataObj.getString("media")

                            productsArray.append(productEntity)
                        }
                        completition(false, productsArray)
                    } else {
                        print("No Data")
                        completition(true, [])
                    }

                }
            catch
            {
                print("Error:",error)
            }

        })
    }
}


ViewController.swift

import UIKit

import DPDropDownMenu
import SVProgressHUD
import SDWebImage

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
…
override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        setupCategoriesMenu();
        refreshProductsData();
    }
...
func refreshProductsData() {
        SVProgressHUD.show(withStatus: "Loading")
        ApiClient.sharedInstance.findProductsByCategory(categoryName: AppGlobals.sharedInstance.menuItems[self.selectedCategoryIndex].title) { (status, products) in
            SVProgressHUD.dismiss()
            if !status {
                AppGlobals.sharedInstance.products = products

                self.products = products

                self.productsCollectionView.reloadData()
            }
        }
    }
…
}


The rest of the code for this example can be seen on GitHub.

Because the most popular method for implementing web services these days is RESTful, this application uses a simple RESTful service to store the products' data and aggregating it as encoded JSON data. Just for testing purposes, we can check  the project pfservice, which is a mockup microservice based on YAML config files for fast and easy simulation of the real products API for the application with a simple configuration- but I will write another tutorial for how to use this service to create a products API microservice.

Topics:
swift ,ios ,e-commerce ,mobile ,mobile app development ,xcode

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}