dilluns, 29 de maig del 2017

Ionic 2. Backup stories part I

When I started this blog, the idea was to practice my English with the hope to improve it, I'm self taught and I think that it is a good way to do it. Normally I write about what I'm doing, and this time is how to do a backup in my app developed with Ionic 2. The point is all of my apps don't use any server to store data, they not ask for special permissions, only the internet access for serve ads and in this case in Android, permission for write in the external storage for save the backup. But this is the second question of this story, so let's start at the beginning.

My app stores the data in a database SQLite and it to do in two tables. The amount of data is not very large and I don't need any more. My first idea was to create a method  that makes a query of all the data and store it in a file in JSON format. Create the backup is really easy and restore it not too complicated. I looked in the Ionic documentation and it provides a File API in Ionic Native for read and write files. Here you can find more info about this.  Well, it seems that I already have all of I need so let's install it.

From a terminal inside the project directory

   ionic plugin add cordova-plugin-file


And
   npm install --save @ionic-native/file




And add the plugin in the app.module.ts. First import it and then we put it on the providers section

import { File } from '@ionic-native/file';

providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, DbService, File, AdMob]

Well, it is ready to use.

But reading the documentation of the plugin I see which it have methods to check, delete and copy files. And I have thought SQLite stores the data in a file so for make a backup I only need copy this file and store it in another directory that finally is the same that should I do with the result of the query. Ok, it's already decided. I will copy the file in a directory accessible to the user.

Now the first step is find the file.  In my database service, I have wrote

openDatabase() { return this.db.openDatabase({ name: 'eDomestic.db', location: 'default', createFromLocation: 1 }) .catch(error => console.error('Error opening database', error)); }


But where is location: default. Well, in Android it is in /data/data/your-app/databases/ or using the plugin File.applicationStorageDirectory + 'databases/'. In iOS it is in /var/mobile/Applications/<UUID>/Library/LocalDatabase/  or using the plugin File.applicationStorageDirectory + 'Library/LocalDatabase/.

First we need to know what system we are using Android or iOS, for that

if (/(android)/i.test(navigator.userAgent)) { this.AndroidDir = this.file.externalRootDirectory; } else if (/(ipod|iphone|ipad)/i.test(navigator.userAgent)) { this.iOSDir = this.file.documentsDirectory; }

AndroidDir and iOSDir contains the destination for the backup. For the origin path

if (this.iOSDir.length > 1) { destPath = this.iOSDir; path = this.file.applicationStorageDirectory + 'Library/LocalDatabase/'; this.translate.get('IOSDOCUMENTSDIRECTORY') .subscribe(value => { dirMessage = value; }); } else { destPath = this.AndroidDir; path = this.file.applicationStorageDirectory + 'databases/'; this.translate.get('ANDROIDDOCUMENTSDIRECTORY') .subscribe(value => { dirMessage = value; }); }

Here, depending of what OS we are using we select a destination and origin or another. And now we can use the plugin for copy the file. But where save the file and why?

In the next entry I will continue explain the as and the why I do it like that.

dilluns, 22 de maig del 2017

Ionic 2. Adding a popover menu


Maybe you want add new features on your app, if this is not an action which it affect only one thing such as realize a backup or restore it, print a summary, etc... for this, a popover is a good option to contain these actions. 

A popover is a dialog that typically appears above other content on the screen and it usually it is positioned at top of the current page, and displays actions that can be carried out. As almost everything in Ionic it is really easy, another thing is as implement these actions. Here you can find more info.

A possible popover could look like to this


Well,  for implement a popover, Ionic provides a PopoverController that we use it for creating, present and dismiss these dialog.

For that we need a template and a controller, I separate it in two files a popover.html for the template and a popover.ts for the controller and I save it in the same directory which contains the page on it appears. It is my way of doing it, but not the unique.

The template can be like this 

<ion-list> <ion-list-header color="primary">Options</ion-list-header> <button ion-item (tap)="backup()">Backup</button> <button ion-item (tap)="restore()">Restore backup</button> </ion-list>

As you see it's just a list

The popover controller looks like

import { Component } from '@angular/core'; import { ViewController, NavParams } from 'ionic-angular'; @Component({ templateUrl: 'popover.html' }) export class PopoverHomePage constructor (public viewCtrl: ViewController, public navParams: NavParams) { } backup() { let data = this.navParams.get('data'); save(data); this.viewCtrl.dismiss(); } restoreBackup() { let data = this.navParams.get('data'); restore(data); this.viewCtrl.dismiss(); } }

And now inside the template where the popover will be showed, in the toolbar section we put a button and at the method which will present the popover we passed him the $event. That variable, contains the original browser event object.

<ion-header> <ion-toolbar color="primary"> <ion-title>eDomestic</ion-title> <ion-buttons right> <button ion-button icon-only color="royal" (tap)="optionsPopover($event)"> <ion-icon name="more"></ion-icon> </button> </ion-buttons> </ion-toolbar> </ion-header>


Inside the controller we put the method which respond to the click button event.

//Show popover menu optionsPopover(event) { let popover = this.popoverCtrl.create(PopoverHomePage, {page: this.pageContent}) popover.present({ ev: event }); }

And in the controller we import PopoverController from ionic-angular. 

First parameter is the component and the second the data that we pass to the popover. Finally we add the popover component in the app.module.ts file and it is ready for work .

And that it's all our popover is ready to be showed.

dilluns, 15 de maig del 2017

Ionic 2. Nested lists

One of the things that surprised me about Ionic 2 it is the ease with which it creates lists, an array in the controller and a *ngFor directive in the template is sufficient to create a list. A little example can be

In the controller

months: string[] = ['January', 'February', 'March', 'April',
                    'May','June', 'July', 'August',
                    'September', 'October', 'November',
                    'December'];

An in the template

<ion-list inset> <button ion-item *ngFor="let month of months" (tap)="monthSelected(month)"> {{ month }} </button> </ion-list>

An the result looks like


Easy and quick. But if you need put a list inside another, the things change.  It's not that it's more difficult, but the things change, starting in the data model and finishing in the template.

This is the way in that I solve this problem, I don't know if it is the best way, but it is the one I used and it works.

First the problem, I need put inside of each month in the list another list with his correspondant expense. So the data that I need are the month name, the total expense of the month, the correspondent expense and his amount.

The result has to be something like this



For that in the controller I have an array with the expenses

expenses: string[] = ['Shopping basket', 'Clothes', 'Electronics', 'Phone', 'Electricity','Fuel', 'Maintenance', 'Transport', 'Hairdressing, ...', 'Health', 'Entertainment','Taxes', 'Rentals'];

And an interface like that

interface Result { month: string; totalMonth: number; amount: number[]; }

An array of Result to which I call result will be the one that will contain the data that we pass to the template. For loop in the result I use the template form of the *ngFor as follows

<template ngFor let-entry [ngForOf]="result"> <ion-list inset> <ion-item> <ion-label class="month">{{ entry.month }}</ion-label>
<ion-label class="expense">{{entry.totalMonth }}$</ion-label> </ion-item> <ion-list inset> <ion-item *ngFor="let expense of entry.amount; let i = index"> <ion-label class="entry">{{ expenses[i] }}</ion-label> <ion-label class="expenseentry">{{ expense }}$</ion-label> </ion-item> </ion-list> </ion-list> </template>

How say here ngForOf is a directive that instantiate a template once per item for an iterable.  For each iteration the entry variable contains an Result, in the first list, the month list, we take the name of the month and the total expense.
Next, we create another list, the expenses list. For that the Result contains an array with the amount of the expense but not the name. The name is in another array (the cause that it is in another array and not in the Result that's not the point) so we will use another value of ngForOf. It is the value index, this value corresponds to index of the current item in the iterable. For obtain the values of the amount array we use an *ngFor, the difference is the introduction of the value index that we use for obtain the name of the expense.

And that's all, our nested list is ready.

dilluns, 8 de maig del 2017

Ionic 2, using ActionSheetController

Recently I have found myself in a situation that has led me to choose between different options. I wanted edit an entry in the database, first I just wanted to modify two fields and use an AlertController for that. Then I thought that I could modify a third field and here appears the problem, this field only can be modified using a checkbox input and a checkbox input can't be mixed with a text input.
For solve this, my first idea was make a new page and use components <ion-select> and <ion-input> but I think it's more natural realize the operation in the same page so that I need  to use an AlertController. For that I have divided the task in two AlertController, one with two text inputs and one with the checkbox input. And for show the two options to user an ActionSheetControllerHere you can find more info.

The first step is import the ActionSheetController  from ionic-angular in our controller
   
   import { NavController, AlertSheetController } from 'ionic-angular'

Next we add the ActionSheetController how a parameter in the constructor
   
   constructor(public navCtrl: NavController, 
               public alertCtrl: AlertSheetController) {

   }   


And now we create a function to present the alert to the user

  showMenu(entry, expense) {
  
    let optionsMenu = this.actionSheetCtrl.create({
      title: '',
      buttons: [
        {
          text: 'Edit entry',
          role: 'edit',
          handler: () => {
            
             this.editEntry(entry, expense);
          }
        },
        {
          text: 'Move to',
          role: 'move',
          handler: () => {
            
             this.moveEntry(entry, expense);
            
          }
        },
        {
          text: 'Cancel',
          role: 'cancel',
          handler: () => {
            optionsMenu.dismiss();
          }
        }
      ]
    });

    optionsMenu.present();
  }

And two functions editEntry(entry, expense) and moveEntry(entry, expense) with his correspondant AlertController to realize the task. 

The result looks like


dilluns, 1 de maig del 2017

Ionic 2, publishing your app. iOS

Continuing with the release process of our new app this time in iOS. The process is a bit different to which we have performed in AndroidHere next to Android description, you can find more documentation about the process.

First in the directory of your app run the command

   cordova build --release ios


This is the only step we use the CLI. When the message BUILD SUCCEEDED appears in the terminal we will have finished with the CLI. We can find the result of the process in platforms/ios/ directory. In this directory what interest us is a Xcode project file ourApp.xcodeproj but for the moment we left it.

The next step is go to the Apple Developer Member Center to register the app. In the Certificates, Identifiers & Profiles choose iOS, tvOS, watchOS




And in the Identifiers select App IDs and next press the (+) button

In this page we must put the name of the app and the Bundle Id, this Id is the same that we have in the config.xml file in our project.

The next step is open the project in Xcode. Once the project is opened we should see the details in the General View. Check if the Bundle Id are correct and if the Deployment Target selected is the desired. In the Archive scheme we select Generic iOS Device and then we select Product -> Archive.

When the Archive Organizer appears  the last step is select the button Upload to App Store... 




And now the last step is go to iTunes Connect, add a new app and follow all the steps to publish the app and finally Submit for review

And remember, every time that the app is updated, you have to modify the config.xml file and update the version,  rebuild and repeat the same steps to upload the app.