Mobile

Ionic 4 - ion-skeleton-text

Over the years, a lot has been said about bounce rate. In essence, you want as many people as possible to stay on your app/page for as long as possible.

One tactic you really should employ is to create something that is engaging for your users. The more they like your content, the more likely is it they will keep coming back - and stay longer.

One problem with that is the more people you compel to give you their time, the harder it becomes for your system to handle all that traffic.

You start improving your system to stay under some magical threshold of 3 seconds and all is looking good. Your app loads fast, doesn’t crash and overall performs as you want it to.

But there is always something extra you can do to can do to shorten the time from app start to app use for your user even if it’s just perceived as being shorter.

Let there be code

Let’s create a blank Ionic project and check a cool new feature in Ionic 4 - ion-skeleton-text.

> ionic start ion-skeleton-text blank

Let’s now go into the home.page.html file and add the content

<!-- home.page.html -->
<ion-content>
  <ion-list>
    <ion-item *ngFor="let item of items">
      {{ item }}
    </ion-item>
  </ion-list>
</ion-content>

We also need some content which we will display with some delay.

// home.page.ts
export class HomePage implements OnInit {
  items: Array<string>;
  constructor() {}

  ngOnInit(): void {
    setTimeout(() => {
      this.items = [
        'Berlin',
        'Buenos Aires',
        'Madrid',
        'New York',
        'Paris',
        'Sydney',
        'Tokyo'
      ];
    }, 2500);
  }
}

If you now execute

> ionic serve

you will see something like this

No loading indication

No loading indication

Adding a loading screen

In order to let the user know that something is going on in the background, we could add a loading indicator which we would remove once the data has been loaded.

// home.page.html
export class HomePage implements OnInit {
  items: Array<string>;
  constructor(private loadingController: LoadingController) {}

  ngOnInit(): void {
    this.loadData();
  }

  async loadData(): Promise<void> {
    const loading = await this.loadingController.create({
      message: 'Loading cities...'
    });

    await loading.present();

    setTimeout(() => {
      this.items = [
        'Berlin',
        'Buenos Aires',
        'Madrid',
        'New York',
        'Paris',
        'Sydney',
        'Tokyo'
      ];

      loading.dismiss();
    }, 2500);
  }
}

I won’t go into the fact that displaying a loading screen should be handled separately because that’s not the point of this post but I know you would never push code like this ;)

Now if we save and check out our browser again we will see a nice loading screen.

Loading screen

Loading screen

Let’s make it a little better

One thing that we know about loading screens is that we don’t really like them. Loading screens on games, apps or anywhere else is something that starts to annoy us quite quickly so we have to keep them as short as possible or remove them completely.

We can try to trick people into believing that the app is already in the process of displaying some content when in fact it’s still waiting for the server to respond. In some cases, it’s just enough to let your users feel like the app is working to make them happy.

When you are courting a nice girl an hour seems like a second. When you sit on a red-hot cinder a second seems like an hour. That’s relativity
— Albert Einstein

If we can display to the user something to keep them happy until they get what they came for we can keep them engaged for longer.

ion-skeleton-text is the answer

ion-skeleton-text is a new UI component which displays a placeholder content instead of the true one.

Implementing it is very straight-forward as you will see soon. Let’s dive right into it.

<!-- home.page.html -->
<ion-content>
  <ion-list *ngIf="items; else skeleton">
    <ion-item *ngFor="let item of items">
      {{ item }}
    </ion-item>
  </ion-list>
</ion-content>

<ng-template #skeleton>
  <ion-list>
    <ion-item *ngFor="let item of [50, 20, 70, 80, 50]">
      <p [ngStyle]="{ width: item + '%' }">
        <ion-skeleton-text animated></ion-skeleton-text>
      </p>
    </ion-item>
  </ion-list>
</ng-template>

What we do here is to simply show the items once they are set (after the 2500 ms) while displaying a few placeholder items in the mean-time.

We also got rid of the loading screen code again in the home.page.ts file to make it look like it was before.

// home.page.ts
export class HomePage implements OnInit {
  items: Array<string>;
  constructor() {}

  ngOnInit(): void {
    this.loadData();
  }

  async loadData(): Promise<void> {
    setTimeout(() => {
      this.items = [
        'Berlin',
        'Buenos Aires',
        'Madrid',
        'New York',
        'Paris',
        'Sydney',
        'Tokyo'
      ];
    }, 2500);
  }
}

Now if you save all you will see something like this:

Skeleton text

Skeleton text

This looks a lot more dynamic than having just a simple spinner and loading message. If you are displaying complex data you can even take advantage of two other cool Ionic component - ion-avatar and ion-thumbnail.

Let’s create one final skeleton-text item which will represent some more complex data.

<!-- home.page.html -->
<ion-content>
  <ion-list *ngIf="items; else skeleton">
    <ion-item *ngFor="let item of items">
      <ion-thumbnail slot="start">
        <img [src]="item.image" />
      </ion-thumbnail>
      <ion-label>
        <h3>City: {{ item.city }}</h3>
        <p>Country: {{ item.country }}</p>
        <p>Population: {{ item.population }}</p>
      </ion-label>
    </ion-item>
  </ion-list>
</ion-content>

<ng-template #skeleton>
  <ion-list>
    <ion-item *ngFor="let item of [1, 2, 3, 4, 5]">
      <ion-thumbnail slot="start">
        <ion-skeleton-text animated></ion-skeleton-text>
      </ion-thumbnail>
      <ion-label>
        <h3>
          <ion-skeleton-text animated style="width: 50%"></ion-skeleton-text>
        </h3>
        <p>
          <ion-skeleton-text animated style="width: 80%"></ion-skeleton-text>
        </p>
        <p>
          <ion-skeleton-text animated style="width: 60%"></ion-skeleton-text>
        </p>
      </ion-label>
    </ion-item>
  </ion-list>
</ng-template>

The typescript code has change also a little:

export class HomePage implements OnInit {
  items: Array<any>;
  constructor() {}

  ngOnInit(): void {
    this.loadData();
  }

  async loadData(): Promise<void> {
    setTimeout(() => {
      this.items = [
        { city: 'Berlin', country: 'Germany', population: '3.5 million', image: '...' },
        { city: 'Buenos Aires', country: 'Argentina', population: '15 million', image: '...' },
        { city: 'Madrid', country: 'Spain', population: '3.3 million', image: '...' },
        { city: 'New York', country: 'USA', population: '19.5 million', image: '...' },
        { city: 'Paris', country: 'France', population: '2.2 million', image: '...' },
        { city: 'Sydney', country: 'Australia', population: '5.4 million', image: '...' },
        { city: 'Tokyo', country: 'Japan', population: '9.2 million', image: '...' }
      ];
    }, 2500);
  }
}

The final result looks now like this:

A more complex example

A more complex example

Now that’s pretty, isn’t it?

The ion-skeleton-text UI component can add a little twist to your app and give the user something shiny to look at while your app does all the heavy lifting. It will keep them focused on something until the final content loads fully and you are able to display it. Giving the user the feeling that the app is running instead of waiting will make them come back and will give you more users to serve.

If you want to check out the code, have a look at it here.

Until next time,
happy coding.

Adding timestamps to photos

While working on an Ionic project, the client asked for a timestamp to be added at the bottom of a taken photo.

After some head scratching, I ended up with the solution below.

onTakePhoto(): void {
  const options: CameraOptions = {
    quality: 30,
    destinationType: this.camera.DestinationType.DATA_URL,
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE,
    targetWidth: 2304,
    targetHeight: 1728
  };

  this.camera.getPicture(options).then(
    (imageData) => {
      this.generateImageWithTimestamp("data:image/jpeg;base64," + imageData);
    },
    (error) => {
      // not important now
    }
  );
}

generateImageWithTimestamp(dataUrl: string): void {
  let image = new Image();
  image.onload = () => {
    let canvas = document.createElement("canvas");
    let context = canvas.getContext("2d");

    canvas.height = image.height;
    canvas.width = image.width;

    context.drawImage(image, 0, 0);

    //adding some styling
    context.font = "80px Arial bold";
    context.textAlign = "center";
    context.fillStyle = "orange";
    context.fillText(
      this.getTimeStamp(),
      image.width / 2, //center
      image.height * 0.97 //close to the bottom
    );

    const finalImage = canvas.toDataURL("image/jpeg", 1);
  };
  image.src = dataUrl;
}

getTimeStamp(): string {
  const date = new Date();

  return `${date.getDate()}. ${date.getMonth() +1}. ${date.getFullYear()}, ${date.getHours()}:${date.getMinutes()}`;
}

We simply take a photo, redraw it on a canvas where we also add the timestamp.

One thing to keep in mind here is that order is important.

In my first attempt I first added the text and then the image which, of course, has overwritten the text. It looks obvious now but it took me a little to figure it out.

Hope this will help you out.

Until next time,
Happy coding.

Deciphering error messages in Ionic

While working on some projects which use the camera to take pictures inside the app I had to add a description for the user to ask for permission.

The code for that is pretty simple:

<edit-config file="*-Info.plist" mode="merge" target="NSPhotoLibraryUsageDescription">
   <string>Please let me take pictures</string>
</edit-config>

After that I wanted to build the application for iOS with the following command:

ionic cordova build ios

What usually finished after 10 seconds with a success message now ended like this:

Now that’s what I call an error message!

Now that’s what I call an error message!

If you are like me you would have no idea what this means. Trying to build again doesn’t solve the problem so it has to be something with this particular change.

After a little bit of digging around I found the fix.

Go into the platforms folder and into ios. There you will find ios.json which holds configurations for the entire application. Locate *-Info.plist and delete the entire object.

After that simply run:

ionic cordova prepare ios

Your build will work again and you can get on with finish your app.

Hope this helps.

Until next time,
happy coding.

Simulating geolocation changes in the VisualStudio Emulator for Android

For almost a year now I have been developing a few mobile applications using Apache Cordova. It's a pretty nice technology (as far as writing HTML and CSS for mobile devices can be) and I have written a few blog posts about it already.

Developing Cordova apps in Visual Studio 2015 is really cool. You get all the power Visual Studio can offer you (despite sometimes hanging or freezing) and on top of that you get excellent emulators created by Microsoft which are miles ahead of the ones Google offers (Genymotion is in second place but I have some problems setting it up on my machine so I can't really talk about it a lot).

While working on my latest project I had to use Geolocation to simulate users movements on streets.

"Easy-peasy", I thought and dug right into it. I downloaded the geolocation plugin (everything is done with plugins in Cordova) and wrote a little piece of code.

    function onSuccess(position) {
      var element = document.getElementById('geolocation');
      element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
                          'Longitude: ' + position.coords.longitude + '<br />' +
                          'Speed: ' + position.coords.speed + '<br />' +
                          'Heading: ' + position.coords.heading + '<br />' +
                          '<hr />';
    }

    function onError(error) {
      alert('code: ' + error.code + '\n' +
            'message: ' + error.message + '\n');
    }

    var watchID = navigator.geolocation.watchPosition(onSuccess, onError, {
      timeout: 30000
    });

What this essentially does is hook up to the geolocation plugin and wait for 30 second to get something back from it. If it get something I grab an element with the ID geolocation and display some information, otherwise I show an error message letting the user know something's wrong.

Another awesome feature of the Visual Studio emulator for Android is the Location tab which lets you pick a route and then select the speed at which you want to move along the route.

I set up my route, hit start and ... nothing happened. What the %$&#??? What's going on? I hook up a phone to my PC and just start it up and ... it works like expected. What the %$&#???

You can imagine how puzzled I was but as I had to get my work done I started working exclusively on the device until I couldn't get away anymore without "moving" on the road.

I asked for help on StackOverflow but the solutions there didn't really help me. Another week passed and I finally found the solution I was looking for.

I looked once again into the docs for the Cordova plugin and I found that the watchPosition function accepts a few more options apart from timeoute.

One of them was enableHighAccurac. The docs say this about this option.

enableHighAccuracy: Provides a hint that the application needs the best possible results. By default, the device attempts to retrieve a Position using network-based methods. Setting this property to true tells the framework to use more accurate methods, such as satellite positioning. (Boolean)

Application needs the best possible results? Sign me up for that!

I added this option to the watchPosition function so that it now looks like this:

    var watchID = navigator.geolocation.watchPosition(onSuccess, onError, {
      timeout: 30000,
      enableHighAccuracy: true 
    });

And lo and behold the damn thing spits out my new position, speed, heading and a lot of other information my way.

I guess that by setting enableHighAccuracy to true forces the phone to use GPS to get it's location and that was what the Location tool was providing from the beginning.

Usually your phone tries a lot of other methods to get it's position (WiFi signals, your carriers antennas, etc.) because they all drain your batter less then listening to the GPS satelites but since this is running on an emulator we have to relay only on the GPS signal which is generated by the phone so we have to tell the phone to ignore the battery and go straight to GPS.

This has been really a frustrating two weeks where I was trying a ton of different things to get this working but I found the light at the end of the tunel and really hope that at least someone will save a few days of research by reading this.

Until next time, happy coding :)