[Ionic Tutorials](How to manage various platforms in your ionic app)

in #utopian-io5 years ago

ionic.jpg
image source

Repository: Ionic Github Repository

Software Requirements:
Visual Studio Code(Or any preferred code editor),
npm, ionic.

What you will learn:
In this tutorial you would learn about how to manage your ionic app on whatever platform you choose to target covering these major concepts

  • How to Register Back Button Action.
  • How to adapt templates based on the platform your program is running on.
  • How to retrieve unique device information based on the used platform.

Tutorial

This tutorial would cover the fundamental knowledge of program your ionic code in a way that it's functionality is adjusted based on whatever platform it may be running on. For example if it is running on a mobile device which may be either android,windows or ios, it would be running on cordova. Or if on a laptop it would be running on MAC'OS and some code needs to be modified for that. Starting up with the basics, registering back button action. This is essential in each platform you choose to run your program on. Back button action registering is what helps you choose what to do with your hardware backbutton on the instance of every page.

Lets get to the code..

Assuming you have ionic globally installed on your system
Start up a new ionic project using
ionic start newProject tabs//This would start a new project using the starter template

Registering Back Button Action

First things first you would need to import an 'ionic/angular' module called Platform.
It comes with every project generated so there isn't need for any npm packages downloads.

Navigate to your home page and import the package from ionic angular like this and add it to your pages constructor

import { Component } from '@angular/core';
import { NavController, AlertController, ActionSheetController,Platform } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public platform: Platform, public actionSheetCtrl: ActionSheetController, public alertCtrl: AlertController, public navCtrl: NavController) {

There are multiple ways of registering back button action for a page, and before making a choice you should know that back button action is triggered regardless of whether the page is the active page or not. Meaning that if your register back button action on a home page it would still be triggered whether you navigate to a new page and tap the hardware back button. As a solution to this they are second arguments to the function called priorities which determine which of the registered action should be carried out. For a beginner however, priorities can be quite confusing so i would recommend unregistering the backbutton action as you leave every page and registering to the new page you are navigating to. To do this we would use the life cycle events

ionViewWillEnter and ionViewWillLeave

The code below

export class HomePage {
  homepagebutton: any;

  constructor(public platform: Platform, public actionSheetCtrl: ActionSheetController, public alertCtrl: AlertController, public navCtrl: NavController) {

  }
  ionViewWillEnter(){
    this.homepagebutton = this.platform.registerBackButtonAction(()=>{
      this.platform.exitApp();//This function will close the app whenever back button is pressed on the home page
    })
    //This returns a function which can be called to unregister the registered back button action
  }
  ionViewWillLeave(){
    this.homepagebutton();//This is so the back button action is unregisterd whenever we leave the page
  }

}

As the comments within the code we register the back button action for each page and unregister it as we are leaving the page so it wont be triggered while we press the back button on another page.

Modifying templates based on the platform

The thing about using one code base is that you want one code base to be able to run on various devices. This can be quite a dilemma when you want the same code to run on a laptop and a phone with the same code because of how the screen size and shape may change. For instance tabs may look good on a phone but look horrible on a desktop version. Here are a few ways you can adapt your template based on what platform your code is running on.
Hide When
This is a commonly neglected ionic property that isn't too familiar to angular user that choose to start up ionic. The alternative to this is referencing the template from the pages .ts file and editing it based on our result. But that would be way more lines of code and way more hectic than using this simple property that does this for us.

You can use this directly from the template file so you don't have to include logic for any of this. This can only be used for screen orientation.
Lets add this to our template file and see how it works

<ion-content>
<div hideWhen="android">
 I am hidden on Android!
</div>

<div hideWhen="ios">
 I am hidden on iOS!
</div>

<div hideWhen="android,ios">
 I am hidden on Android and iOS!
</div>

<div hideWhen="portrait">
 I am hidden on Portrait!
</div>

<div hideWhen="landscape">
 I am hidden on Landscape!
</div>
</ion-content>

You wouldn't be able to test this out in your chrome browser so you would need to compile this for either android or ios and test this out of the emulator.
You can use this commands

ionic cordova build android -l//Test this out in an emulator

Another way of determining what platform within your logic file comes with an inbuilt function
The code below

//define the variable before the constructor
usedplatform: string;
 
constructor(){
....other code here....


//for example
determinePlatform(){
    if(this.platform.is('cordova')){
      this.usedplatform = 'cordova';
    }
    if(this.platform.is('ipad')){
      this.usedplatform = 'ipad';
    }
  }

Simply bind this to a button like this

<h1>{{ usedplatform }}</h1>

This can be used to detect the platform the program is running on

Unique Uid

Every device comes with a unique id. This would be very valid if you need to know a user regardless of whether he uninstalls and reinstalls your app. Because the devices id would never change. There is a cordova plugin that is available which would help you detect the devices id in a string format which you can use.

To get started install the npm package and cordova plugin like this

 ionic cordova plugin add cordova-plugin-uniquedeviceid// Use these command in your terminal
 npm install --save @ionic-native/unique-device-id

And then in your app.module.ts file add them as your providers

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';

import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { UniqueUID } from '@ionic-native/Unique-uid'//Import here

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    UniqueUID//Included to the providers here
  ]
})
export class AppModule {}

And then you can use it within your page like this

import { UniqueDeviceID } from '@ionic-native/unique-device-id';

constructor(private uniqueDeviceID: UniqueDeviceID) { }

...

this.uniqueDeviceID.get()
  .then((uuid: any) => console.log(uuid))//This is the uid for the device
  .catch((error: any) => console.log(error));

You can find the code to this tutorial in github
Here

Sort:  

Thank you for your contribution @yalzeee.
After analyzing your tutorial we have the following suggestions:

  • We suggest you improve the structure of your tutorial. Always separate the paragraphs so that your tutorial is easier to read.

  • It is important to have images with the results of what is developed, so the reader has the perception of what was done.

Thank you for your work in developing this tutorial. We've been waiting for more tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Hello! I find your post valuable for the wafrica community! Thanks for the great post! We encourage and support quality contents and projects from the West African region.
Do you have a suggestion, concern or want to appear as a guest author on WAfrica, join our discord server and discuss with a member of our curation team.
Don't forget to join us every Sunday by 20:30GMT for our Sunday WAFRO party on our discord channel. Thank you.

Hi @yalzeee!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @yalzeee!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.30
TRX 0.12
JST 0.034
BTC 63815.31
ETH 3124.40
USDT 1.00
SBD 3.99