Native Mobile Application Development for eCommerce

This entry was posted on December 26, 2019 by Filip Komatinović, Android & iOS Developer.

Native Mobile App

The Role of Mobile Devices in eCommerce

Over the years, mobile devices have become more of a necessity rather than an accessory. Not long ago, mobile devices were used only for communication. Nowadays, mobile devices are everywhere and are used for a variety of purposes such as transportation, paying taxes, navigation and many other purposes. Mobile app solutions have quickly been growing at an exponential rate. One of the fastest-growing mobile app usages is in eCommerce.

Ecommerce is becoming more and more popular due to the ease and convenience that mobile devices bring to the process of online shopping. In 2019, the number of American digital buyers is estimated to be 215 million.

The Benefits of Mobile eCommerce

Mobile users are using their devices more and more to help them purchase various products they find appealing. Those products can range from clothing, furniture, electronics, to even groceries. These users now have the ability to browse and discover various products on-the-go. They can also easily access product reviews that have been written by previous purchasers on their mobile devices before making purchases. This information can have a large influence on potential customers whether they want to spend their money or not.

Mobile eCommerce apps allow their users to purchase online and get the wanted products at their doorstep. The benefit of using mobile eCommerce apps is their usage regardless of time and space. Mobile apps can be used on the bus, in the shopping mall, while waiting at the airport, etc. On the contrary, desktop applications limit their users to use them from only one place, be it at home or at work. Many companies can benefit from selling their products even when their stores are closed after the working time is up. This can help increase sales by removing certain purchasing limitations.

Importance of eCommerce Mobile App Marketing

Over the years, a mobile app has become an important strategy for many brands. It can boost brand recognition and drive revenue if utilized optimally. To fully take advantage of having an eCommerce app, brands should be strategic in executing their app marketing campaigns. Whether it is to acquire new loyal users who will make purchases, retarget purchasers in old or existing apps to promote the new app, or re-engage lapsed users - programmatic advertising can help.

Magento 2 REST API

Magento exposes different REST endpoints depending on the type of user making the requests. You must request and include a security token to gain access to the Customer and Admin REST API endpoints. Magento REST API calls are crucial for developing the mCommerce application that is built for Magento 2 website. Every necessary API call must be handled with some of the mobile networking libraries I will be describing later in this text.

Synchronous Endpoints

Each of the following links leads to a list of REST endpoints specific to a user type:

Asynchronous Endpoints

You can run POST and PUT endpoints asynchronously while the async.operations.all message queue consumer is active. Asynchronous web endpoints provide information about asynchronous routes, payloads, and responses.

IOS and Android Libraries for Networking

Since mCommerce application needs to be in constant conjunction with REST API of the eCommerce website, in our case Magento 2, HTTP networking libraries will be needed to do so. In this paragraph, mobile networking libraries will be described for handling REST API calls. 

Alamofire

Alamofire is an HTTP networking library written in Swift for devices that use iOS.


Requirements:

  • iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+
  • Xcode 10.2+
  • Swift 5+

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'Alamofire', '~> 5.0.0-rc.3'

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your Cartfile:

github "Alamofire/Alamofire" "5.0.0-rc.3"

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler. It is in early development, but Alamofire does support its use on supported platforms.

Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.0.0-rc.3")
]

Manually

If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually.

Embedded Framework

  • Open up Terminal, cd into your top-level project directory, and run the following command if your project is not initialized as a git repository:
 $ git init
  • Add Alamofire as a git submodule by running the following command:
 $ git submodule add https://github.com/Alamofire/Alamofire.git
  • Open the new Alamofire folder, and drag the Alamofire.xcodeproj into the Project Navigator of your application’s Xcode project. It should appear nested underneath your application’s blue project icon. Whether it is above or below all the other Xcode groups does not matter.
  • Select the Alamofire.xcodeproj in the Project Navigator and verify the deployment target matches that of your application target.
  • Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the Targets heading in the sidebar.
  • In the tab bar at the top of that window, open the General panel.
  • Click on the + button under the Embedded Binaries section.
  • You will see two different Alamofire.xcodeproj folders each with two different versions of the Alamofire.framework nested inside a Products folder. It does not matter which Products folder you choose from, but it does matter whether you choose the top or bottom Alamofire.framework.
  • Select the top Alamofire.framework for iOS and the bottom one for macOS. You can verify which one you selected by inspecting the build log for your project. The build target for Alamofire will be listed as either Alamofire iOS, Alamofire macOS, Alamofire tvOS or Alamofire watchOS.
  • And that’s it!

The Alamofire.framework is automatically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.

Here is an example from our mCommerce application: 

    static func getSingleCategory(categoryId: String, completion: @escaping (_  category: Category) -> Void) {
        AF.request(Urls.shared.singleCategoryUrl(categoryId: categoryId), method: .get, headers: AFHelper.getHeader(token: TokenManager.getAdminToken())).response { response in
            self.printResponse(response: response)
            if let data = response.data {
                    let decoder = JSONDecoder()
                    do {
                        let categories = try decoder.decode(Category.self, from: data)
                        //print(options)
                        completion(categories)
                        
                    } catch {
                        print(error.localizedDescription)
                    }
 
            }
        }
    }

Retrofit 2 

Retrofit is a REST Client for Java and Android. It makes it easy to retrieve and upload JSON or XML via a REST-based web service. In Retrofit, you can configure which converter is used for the data serialization. Typically for JSON, you use GSon, but you can add custom converters to process XML or other protocols. Retrofit uses the OkHttp library for HTTP requests.

How to use Retrofit

To work with Retrofit it is necessary to define a model class that is serialized to JSON. Then, you have to define Interface that defines the possible HTTP operations. And finally, it is important to define Retrofit. Builder class - Instance which uses the interface and the Builder API to allow defining the URL endpoint for the HTTP operations.

Every method of an interface represents one possible API call. It must have an HTTP annotation (GET, POST, etc.) to specify the request type and the relative URL. The return value wraps the response in a Call object with the type of the expected result.

@GET
Single<OrdersResponse> getRecentOrdersRX(@Url String url);

 

This method can be called from another class as shown in the following example:
 

   public void getRecentOrders(CompositeDisposable disposable, MutableLiveData<OrdersResponse> ordersMutableLiveData, MutableLiveData<Boolean> loading, String customerId) {
        disposable.add(RetrofitHelper.getInstance().getApi(true).getRecentOrdersRX(Urls.shared.myRecentOrders(customerId))
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableSingleObserver<OrdersResponse>() {
                                   @Override
                                   public void onSuccess(OrdersResponse ordersResponse) {
                                       ordersMutableLiveData.setValue(ordersResponse);
                                       loading.setValue(false);
                                   }

                                   @Override
                                   public void onError(Throwable e) {
                                       loading.setValue(false);
                                       e.printStackTrace();
                                   }
                               }
                ));
    }

Authentication with OkHttp Interceptors

If you have more calls that require you to authenticate, you can use an interceptor for this. An interceptor is used to modify each request before it is performed and alter the request header. The advantage is that there is no need for adding the @Header("Authorization") to each API method definition.

In the code below, it is checked whether httpClient has or has not our interceptor.

static <S> S createService(boolean admin) {

   AuthenticationInterceptor interceptor = new AuthenticationInterceptor(admin);
   if (!httpClient.interceptors().contains(interceptor)) {
       httpClient.addInterceptor(interceptor);
   }

   if (!httpClient.interceptors().contains(logging)) {
       httpClient.addInterceptor(logging);
   }

   builder.client(httpClient.build());
   retrofit = builder.build();

   return retrofit.create((Class<S>) RetrofitApi.class);
}

In order to define your own Interceptor you can do the same thing that we have done in our application - create a custom class AuthenticationInterceptor and override its intercept function:

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

class AuthenticationInterceptor implements Interceptor {

   boolean admin;

   AuthenticationInterceptor(boolean admin) {
       this.admin = admin;
   }

   @Override
   public Response intercept(Chain chain) throws IOException {

Further in this code, a bearer token is added to the header of the HTTP request and thus the authentication is done.

Example of an eCommerce Application

Here is one of many examples of eCommerce applications used for purchasing different kinds of products. Usually, the navigation bar is necessary for guiding the user through the application. Also, the user should be able to see all the categories and products of the selected category inside of some fragment, in case of Android application, or View Controller, in case of iOS application. Cart review and payment information are also mandatory for any kind of eCommerce applications. 

 

eCommerce Mobile App

1. eCommerce Mobile App, Example

 

Safety is absolutely important, so any kind of payment should be made as secure as possible.

Conclusion

In our mCommerce application, the mobile application communicates with Magento 2 REST API and any action done inside the mobile application results in calling some of the network calls handled by networking libraries. Implementation of this kind of application also needs solving a lot of security issues and also the implementation of safe buying and safe ordering products that customers want to buy. Our company is dedicated and willing to place one of the best mCommerce applications on the mobile application market. So stay tuned for the upcoming news about this application and the release date for both iOS and Android versions of the application.

 

Sources:

https://devdocs.magento.com/redoc/2.3/index.html
https://alamofire.github.io/Alamofire/
https://aarki.com/blog/the-role-of-mobile-devices-in-ecommerce

This entry was posted in Mobile Applications and tagged Web Development, SyncIt Group, Web, eCommerce, Mobile Applications, Mobile Apps, Mobile App Development, Android, Android Development, iOS, iOS Development, eCommerce Apps, mCommerce, mCommerce Apps, Native Apps, Native Mobile Apps on December 26, 2019 by Filip Komatinović, Android & iOS Developer .