Contact Us

Build Offline Ionic 6 Applications

 - 
May 19, 2022
Build Offline Ionic 6 Applications

Mobile applications are very useful in many use cases especially when they are used to manage an organization or a system such as inventory management, time management, project organization and so many other use cases. The problem is in most cases you need to have internet connection to use these kind apps, but what if you don’t have internet or you want to use the application in an offline mode. That is why in this article we will explain how to build Offline Ionic 6 Applications

Imagine you can manage your inventory or your organization without using internet, that would be very wonderful. There are actually some solutions to this problem, we can handle the app and customize it to be working even when there is no internet connection.

In this article we will list and explain all the steps you need to take to build your first offline mobile application. We will build an Ionic 6 application that works in an offline state, by cashing data coming from our API and use it later when there is no connection.

Why would you want to build an offline application ?

Building a mobile application that won’t crash when there is no internet is a very important step that you have to take if you own a mobile app, because that will help your users have a great user experience with the app and also keep using it even if they are offline.

There are some powerful use cases that will force you add this functionality to your mobile app such as inventory management. If your app’s goal is to manage an inventory with products, orders, invoices, clients… It would be very helpful to have your app working offline because sometimes you will need to see some products or download an invoice to give to a client instantly but you don’t have internet.

The application won’t be 100% offline because this is impossible. In some use cases we absolutely need the internet connection to perform some actions such as saving data in the database, deleting data from the database… In reality, that depends on your business logic in the app, you can for example save the data in localStorage while you are offline, and once the internet is back you immediately save it to the database.

Another advantage of having the offline functionality implemented in your application is the performance. You will notice that your app will be so performant, fast and easy to use because requests are not sent every time randomly.

There are a lot of other advantages of having an offline version of your mobile application, but we can not list all of them in this article because it’s not the purpose of this post.

Ionic 6 offline apps logic

Ionic 6 and Angular 14

In this section, we will see how building an Ionic mobile application with the offline functionality really works and what are the most important steps that you must follow to achieve it.
First of all, we will need to store the data required by the app in the local storage of the application using the LocalStorage API in our case with Ionic. The local storage will help us save the most important data that our application needs to keep working even when running out of connection.

If the application has a small space and can not afford all the data coming from the database, we can use the phone storage to save the data in there and then use it when there is a need.

Actually the logic of handling this kind of problems depends on the application and its complexity. If you have a huge database and the data is big then you can start using the phone storage or the session, otherwise you can still go with the local storage of the mobile application.

Another important data to store is the API requests, we can store them in the local storage directly since they don’t have a huge size. Along with the API request we will store the status which will help us know if the API stores have been successfully served or not yet, and that will help us make requests to the local storage instead of the server.

Setting up an Ionic 6 project

In this section we will follow a set of steps that will help us achieve our goal in this post which is to build an offline version of an Ionic 6 application.

  1. Setup Ionic 6 project.
  2. Install and setup the required packages and plugins.
  3. Work with Storage API in Ionic (Get, Set and Remove values from LocalStorage).
  4. Check Internet connectivity and get data based on that.
  5. Testing our application.

Setup Ionic 6 project

Setting up an Ionic 6 project is very easy, first make sure you have the latest version of Ionic installed in your computer. Once you have installed Ionic 6 in your device go ahead and run the following command to build a new Ionic 6 project.

ionic start offline-app-project blank –cordova

This command will create a new blank Ionic 6 project which you can open with your favorite code editor (I personally love vs code). Since we will use cordova in this project we added the –cordova option in the command which will directly integrate cordova plugins to the app.

Install and setup the required packages and plugins

In order to detect if the user have an internet connection or not, we need to install some additional cordova plugins. Make sure you are in the path of your app and run the following command.

ionic cordova plugin add cordova-plugin-network-information
npm install @ionic-native/network

Using these two packages we will be able to detect whether there is an internet connection or not.

Now, in order to maintain the user data in the local storage table, we have to install some other plugins. These two plugins will help us store data in an offline mode.

ionic cordova plugin add cordova-sqlite-storage
npm install --save @ionic/storage

Go to the app.module.ts file and add the following snippet of code which will setup the plugins we just installed and also setup the services of our app.

Basically, we have to add some modules to the imports array in the app.module.ts file like Network, IonicStorageModule, HttpClientModule…

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { HttpClientModule } from  '@angular/common/http';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule, 
    HttpClientModule,
    IonicStorageModule.forRoot()
  ],
  providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    Network
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

Work with Storage API in Ionic (Get, Set and Remove values from LocalStorage)

Ionic is a very powerful mobile framework that includes a lot of advanced concepts like the Storage API which helps store data in the local storage. Using the Storage API is quit easy because what you need to do basically is import the Storage service in the constructor and then start using it with the provided functions.

The following snippet of code shows you how to use the Ionic Storage API in your home page.

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(private storage: Storage) {

  }

  // Add new value to the Ionic Storage
  setNewValue(key: string, value: any) {
    this.storage.set(key, value).then((resp) => {
      console.log(resp);
      
    }).catch((err) => {
      console.log(err);
      
    });
  }

  // get an item from the storage
  getValue(key: string) {
    this.storage.get(key).then((resp) => {
      console.log(resp);
      
    }).catch((err) => {
      console.log(err);
    })
  }

  // remove an item from the storage
  removeItem(key: string) { 
    this.storage.remove(key).then((resp) => {
      console.log(resp);
      
    }, (err) => {
      console.log(err);
      
    })
  }

  // get all the items in the storage
  getAllItems() {
    this.storage.keys().then((resp) => {
      console.log(resp);
      
    }, (err) => {
      console.log(err);
      
    })
  }

}

Let’s explain each function provided by the Ionic Storage library.

get()

The get() function will get an item stored in the localStorage area. It takes a single argument which is the key of the item that you want to access. It returns the value of that item.

set()

The set() function is the opposite of the get() function, instead of getting an item from the Local storage we will store an item in there. It takes two arguments, the first one is the key and the second is the value of the item you want to store.

remove()

This function is actually self explanatory. Its job is to remove an item from the local storage by taking the key of that item as argument, and it returns nothing.

keys()

The last function we will cover is the keys() function which is very useful because it gets all the values that was stored before in the local storage. This function does not take any arguments.

Check Internet connectivity and get data based on that.

Now that we know how to use the loacal storage by using all the previous functions, let’s have a look on a very important task that we must achieve to solve the offline problem, which is detecting whether the user is connected or not.

In order to implement this functionality, we will use two main methods (onConnect() and onDisconnect()) and we will subscribe to them to get the current state of the connection.

While detecting changes in the connection, we can display a toast that show to display the current state to the user.

At this point we are ready to test our application and see if it works in an offline mode or not.

Testing our application

First of all, we need to build our application for either Android or IOS platform, and then run the app in action in both platforms.

For Android : 

ionic cordova platform add ios

For IOS :

ionic cordova platform add ios

Now, let’s build our application 

For Android :

ionic cordova build android

For IOS :

ionic cordova build ios

Now that we have built our application, let’s run it and test it.

For Android :

ionic cordova run android -l

For IOS

ionic cordova run ios -l

As you can see in the following image, the application is working greatly, and the data is displaying in the offline mode.

Conclusion

Ionic 6 is a very powerful and amazing mobile development framework that help us build great mobile applications especially when it support some powerful features like the one we saw today in this article.

In this article we learnt how to use the local store provided by the Storage API from Ionic and store our data in there to use whene there is no internet connection. We also learnt how to detect the change of the internet connection and based on that use either the data stored in local store or the data stored in the database.

Check out this article if you want to learn how to read an API using Ionic 6.

Web Design Services

Looking for a web design agency to bring your business online and build the website you need to get more high quality clients ?
GrowYourBusiness.tech agency is ready to help you build your beautiful looking website.

Latest Blogs

We are a team of creative thinkers and problem solvers dedicated to expanding the limits of what is possible by helping brands achieve their goals.

Social Media

Copyright © 2021 Grow Your Business. All rights reserved.
crossmenu