iOS 13: A Bucket of New Features for IPad and iPhone App Developers

Here you will get to know about the essential feature of ios 13 that will disrupt mobile app development industry. Continue Reading

Display Weather Information in a NativeScript With Angular Android and iOS Mobile App

Display Weather Information in a NativeScript With Angular Android and iOS Mobile App

In this tutorial, we're going to develop an application for Android and iOS with NativeScript.

In this tutorial, we're going to develop an application for Android and iOS with NativeScript.

I am a huge fan of NativeScript and have been for a long time. While HERE doesn't currently offer an official NativeScript SDK for building Android and iOS applications, it shouldn't stop you from using HERE with NativeScript because most APIs can be accessed over HTTP.

A few months ago, I had written a tutorial around using the HERE Weather API with Angular which many of you found very useful. To make this tutorial mobile friendly, I thought NativeScript would be a great candidate.

In this tutorial, we're going to expand what we saw in the web version and take it to Android and iOS with NativeScript.

To get an idea of what we hope to accomplish, take a look at the following image:

Nothing too fancy is happening in the above picture. We are collecting the 7 day forecast and displaying it in a list with the appropriate weather icons. All of this data, including the icon, is returned as part of the API response.

To proceed with this tutorial, you will need to have NativeScript and Angular CLI installed and properly configured, along with a HERE Developer Portal account.

Create a New NativeScript With Angular Project

Assuming you've got NativeScript ready to go, we can create a new Angular templated project for use with this project. From the command line, execute the following command:

tns create here-weather-project --template tns-template-blank-ng

Since we'll be using HTTP to communicate with REST APIs, we won't need to install any special plugins. As we reach a certain point in the tutorial we will install a JavaScript library for time conversions, but it isn't necessary for our project and can wait.

Request Weather Forecast Information From the HERE Weather API

To be successful with the HERE Weather API, we'll need to make use of the the Angular HttpClient module. To do this, we need to make some changes to the project's src/app/app.module.ts file:

import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
        NativeScriptModule,
        AppRoutingModule,
        HttpClientModule
    ],
    declarations: [
        AppComponent
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
export class AppModule { }

In the above code, notice that the HttpClientModule was imported and then added to the imports array of the @NgModule block. With it added, we can start using it in our components and services.

To keep this example simple, we will not be creating any new services or components. We're going to leverage the HomeComponent that should already exist as part of the NativeScript template.

Open the project's src/app/home/home.component.ts file and include the following:

import { Component, OnInit } from "@angular/core";
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Component({
    moduleId: module.id,
    selector: "home",
    templateUrl: "./home.component.html"
})
export class HomeComponent implements OnInit {
    private appId: string;
    private appCode: string;
    public weather: any;
    public constructor(private http: HttpClient) { }
    public ngOnInit() { }
    public getWeather(coordinates: any) { }
}

Because we know we'll be using the HttpClient class, we need to import it along with the HttpParams class. We then need to start configuring each of our methods.

In the constructor method, we inject the HttpClient, but we also need to define our HERE application tokens:

public constructor(private http: HttpClient) {
    this.appId = "HERE-APP-ID";
    this.appCode = "HERE-APP-CODE";
}

Make sure to replace the actual tokens with those found in your HERE Developer Portal account. With the tokens defined, let's start creating the HTTP request to the HERE Weather API.

Within the file, make the getWeather method look like the following:

public getWeather(coordinates: any) {
    let params = new HttpParams({
        fromObject: {
            "product": "forecast_7days_simple",
            "latitude": coordinates.latitude,
            "longitude": coordinates.longitude,
            "app_id": this.appId,
            "app_code": this.appCode
        }
    });
    this.http.get("https://weather.cit.api.here.com/weather/1.0/report.json", { params: params })
        .pipe(map(result => (<any>result).dailyForecasts.forecastLocation))
        .subscribe(result => {
            this.weather = result.forecast;
        }, error => {
            console.error(error);
        });
}

The above code is where the magic happens. After being provided a set of latitude and longitude coordinates, we can construct the request with the parameters found in the documentation. These parameters also include our application tokens.

With the parameters properly formatted, we can make the request and store the response in the weathervariable. In our scenario, we only care about the forecastLocation information. There are plenty of other parameters and response data to look at as part of the HERE Weather API.

To execute this function when the component initializes, we can make use of the ngOnInit method:

public ngOnInit() {
    this.getWeather({ latitude: 37.7397, longitude: -121.4252 });
}

In the above example, we are requesting weather information for Tracy, CA. As of now we aren't displaying the information, only obtaining it. To display it, we can visit the project's src/app/home/home.component.html file:

<ActionBar class="action-bar">
    <Label class="action-bar-title" text="TRACY, CA"></Label>
</ActionBar>
<GridLayout class="page">
    <ListView [items]="weather" class="list-group">
        <ng-template let-forecast="item">
            <GridLayout class="list-group-item" rows="auto, auto" columns="50, *">
                <Image [src]="forecast.iconLink" rowSpan="2" row="0" col="0"></Image>
                <Label text="{{ forecast.highTemperature }}C" row="0" col="1" class="p-x-5"></Label>
                <Label text="{{ forecast.utcTime }}" row="1" col="1" class="p-x-5"></Label>
            </GridLayout>
        </ng-template>
    </ListView>
</GridLayout>

The above XML will create a nicely formatted list of data. The data will include the image, the temperature in Celsius, and the time. However, the time won't be formatted and the we may be more interested in Fahrenheit format for the temperature.

This is where we can start formatting our data.

Change the Response Format With Angular Pipes

There are plenty of ways to format our data, but in Angular, it might be best to create a pipe for our needs. We can actually create two pipes, one for the Fahrenheit conversion and one for the time formatting.

To do this, execute the following commands from within your project:

ng g pipe fahrenheit 
ng g pipe moment

The above commands will create two pipes. As you might have noticed, we'll be using Moment.js for our time conversions. This means we need to install it like mentioned earlier in the tutorial. To do this, execute the following from the command line:

npm install moment --save

We're going to start with our Celsius to Fahrenheit conversion. Open the project's src/app/fahrenheit.pipe.ts file and include the following:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'fahrenheit'
})
export class FahrenheitPipe implements PipeTransform {
    public transform(value: any, args?: any): any {
        return ((value * (9 / 5)) + 32).toFixed(2);
    }
}

We're using a standard formula during our transformation to make this possible. Before we try to use this pipe, let's finish the MomentPipe as well. Open the project's src/app/moment.pipe.ts and include the following:

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from "moment";
@Pipe({
name: 'moment'
})
export class MomentPipe implements PipeTransform {
    public transform(value: any, args?: any): any {
        return moment(value).format("MMMM DD, YYYY");
    }
}

There is one more step that must be taken before we can actually use the FahrenheitPipe and MomentPipepipes. We need to include them as part of our module. However, we aren't going to include them to our project's src/app/app.module.ts file. If any reference to these pipes exist there, go ahead and remove them. Instead, we're going to add them to the project's src/app/home/home.module.ts file like so:

import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptCommonModule } from "nativescript-angular/common";
import { HomeRoutingModule } from "./home-routing.module";
import { HomeComponent } from "./home.component";
import { FahrenheitPipe } from '../fahrenheit.pipe';
import { MomentPipe } from '../moment.pipe';
@NgModule({
    imports: [
        NativeScriptCommonModule,
        HomeRoutingModule
    ],
    declarations: [
        HomeComponent,
        FahrenheitPipe,
        MomentPipe
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
export class HomeModule { }

At this point in time we can actually use the two pipes in our application. Go back into the project's src/app/home/home.component.html file so we can make a small adjustment.

Take note of the following:

<GridLayout class="list-group-item" rows="auto, auto" columns="50, *">
    <Image [src]="forecast.iconLink" rowSpan="2" row="0" col="0"></Image>
    <Label text="{{ forecast.highTemperature }}C / {{ forecast.highTemperature | fahrenheit }}F" row="0" col="1" class="p-x-5"></Label>
    <Label text="{{ forecast.utcTime | moment }}" row="1" col="1" class="p-x-5"></Label>
</GridLayout>

In our GridLayout we are now piping the data returned from the API into the FahrenheitPipe and MomentPipepipes.

Again, not entirely necessary, but helpful long term for larger projects.

Conclusion

You just saw how to use the HERE Weather API in your NativeScript with Angular project. The HERE Weather API is much more involved than just a 7 day forecast, but for the simplicity of the example, that is the only data we decided to work with.

This tutorial was a followup to the weather with Angular tutorial I had written prior which was strictly for the web.

Which Mobile App Development Techniques Turn App Users From Dormant To Dynamic?

Mobile app engagement and mobile app retention are two critical metrics that serve real insight into the success of a mobile application. By given blog, you will get to know how mobile app development service convinces users to engage and retain. <a href="https://www.cmarix.com/which-mobile-app-development-techniques-turn-app-users-dormant-to-dynamic/?utm_source=SB" target="_blank">Readmore</a>

Mobile app engagement and mobile app retention are two critical metrics that serve real insight into the success of a mobile application. By given blog, you will get to know how mobile app development service convinces users to engage and retain. Readmore

How to Build Mobile Apps with Angular, Ionic 4, and Spring Boot

How to Build Mobile Apps with Angular, Ionic 4, and Spring Boot

Run Your Ionic App on Android. Make sure you're using Java 8. Run ionic cordova prepare android. Open platforms/android in Android Studio, upgrade Gradle if prompted. Set launchMode to singleTask in AndroidManifest.xml. Start your app using Android Studio...

In this brief tutorial, I’ll show you to use Ionic for JHipster v4 with Spring Boot and JHipster 6.

To complete this tutorial, you’ll need to have Java 8+, Node.js 10+, and Docker installed. You’ll also need to create an Okta developer account.

Create a Spring Boot + Angular App with JHipster

You can install JHipster via Homebrew (brew install jhipster) or with npm.

npm i -g [email protected]

Once you have JHipster installed, you have two choices. There’s the quick way to generate an app (which I recommend), and there’s the tedious way of picking all your options. I don’t care which one you use, but you must select OAuth 2.0 / OIDCauthentication to complete this tutorial successfully.

Here’s the easy way:

mkdir app && cd app

echo "application { config { baseName oauth2, authenticationType oauth2, \
  buildTool gradle, testFrameworks [protractor] }}" >> app.jh

jhipster import-jdl app.jh

The hard way is you run jhipster and answer a number of questions. There are so many choices when you run this option that you might question your sanity. At last count, I remember reading that JHipster allows 26K+ combinations!

The project generation process will take a couple of minutes to complete if you’re on fast internet and have a bad-ass laptop. When it’s finished, you should see output like the following.

OIDC with Keycloak and Spring Security

JHipster has several authentication options: JWT, OAuth 2.0 / OIDC, and UAA. With JWT (the default), you store the access token on the client (in local storage). This works but isn’t the most secure. UAA involves using your own OAuth 2.0 authorization server (powered by Spring Security), and OAuth 2.0 / OIDC allows you to use Keycloak or Okta.

Spring Security makes Keycloak and Okta integration so incredibly easy it’s silly. Keycloak and Okta are called "identity providers" and if you have a similar solution that is OIDC-compliant, I’m confident it’ll work with Spring Security and JHipster.

Having Keycloak set by default is nice because you can use it without having an internet connection.

To log into the JHipster app you just created, you’ll need to have Keycloak up and running. When you create a JHipster project with OIDC for authentication, it creates a Docker container definition that has the default users and roles. Start Keycloak using the following command.

docker-compose -f src/main/docker/keycloak.yml up -d

Start your application with ./gradlew (or ./mvnw if you chose Maven) and you should be able to log in using "admin/admin" for your credentials.

Open another terminal and prove all the end-to-end tests pass:

npm run e2e

If your environment is setup correctly, you’ll see output like the following:

> [email protected] e2e /Users/mraible/app
> protractor src/test/javascript/protractor.conf.js

[16:02:18] W/configParser - pattern ./e2e/entities/**/*.spec.ts did not match any files.
[16:02:18] I/launcher - Running 1 instances of WebDriver
[16:02:18] I/direct - Using ChromeDriver directly...


  account
    ✓ should fail to login with bad password
    ✓ should login successfully with admin account (1754ms)

  administration
    ✓ should load metrics
    ✓ should load health
    ✓ should load configuration
    ✓ should load audits
    ✓ should load logs


  7 passing (15s)

[16:02:36] I/launcher - 0 instance(s) of WebDriver still running
[16:02:36] I/launcher - chrome #01 passed
Execution time: 19 s.

OIDC with Okta and Spring Security

To switch to Okta, you’ll first need to create an OIDC app. If you don’t have an Okta Developer account, now is the time!

Log in to your Okta Developer account.

  • In the top menu, click on Applications
  • Click on Add Application
  • Select Web and click Next
  • Enter JHipster FTW! for the Name (this value doesn’t matter, so feel free to change it)
  • Change the Login redirect URI to be <a href="http://localhost:8080/login/oauth2/code/oidc" target="_blank">http://localhost:8080/login/oauth2/code/oidc</a>
  • Click Done, then Edit and add <a href="http://localhost:8080" target="_blank">http://localhost:8080</a> as a Logout redirect URI
  • Click Save

These are the steps you’ll need to complete for JHipster. Start your JHipster app using a command like the following:

SPRING_SECURITY_OAUTH2_CLIENT_PROVIDER_OIDC_ISSUER_URI=https://{yourOktaDomain}/oauth2/default \
  SPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_OIDC_CLIENT_ID=$clientId \
  SPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_OIDC_CLIENT_SECRET=$clientSecret ./gradlew

Create a Native App for Ionic

You’ll also need to create a Native app for Ionic. The reason for this is because Ionic for JHipster is configured to use PKCE(Proof Key for Code Exchange). The current Spring Security OIDC support in JHipster still requires a client secret. PKCE does not.

Go back to the Okta developer console and follow the steps below:

  • In the top menu, click on Applications
  • Click on Add Application
  • Select Native and click Next
  • Enter Ionic FTW! for the Name
  • Add Login redirect URIs: <a href="http://localhost:8100/implicit/callback" target="_blank">http://localhost:8100/implicit/callback</a> and dev.localhost.ionic:/callback
  • Click Done, then Edit and add Logout redirect URIs: <a href="http://localhost:8100/implicit/logout" target="_blank">http://localhost:8100/implicit/logout</a> and dev.localhost.ionic:/logout
  • Click Save

You’ll need the client ID from your Native app, so keep your browser tab open or copy/paste it somewhere.

Create Groups and Add Them as Claims to the ID Token

In order to login to your JHipster app, you’ll need to adjust your Okta authorization server to include a groups claim.

On Okta, navigate to Users > Groups. Create ROLE_ADMIN and ROLE_USER groups and add your account to them.

Navigate to API > Authorization Servers, click the Authorization Servers tab and edit the default one. Click the Claims tab and Add Claim. Name it "groups" or "roles" and include it in the ID Token. Set the value type to "Groups" and set the filter to be a Regex of .*. Click Create.

Navigate to <a href="http://localhost:8080" target="_blank">http://localhost:8080</a>, click sign in and you’ll be redirected to Okta to log in.

Enter the credentials you used to signup for your account, and you should be redirected back to your JHipster app.

Generate Entities for a Photo Gallery

Let’s enhance this example a bit and create a photo gallery that you can upload pictures to. Kinda like Flickr, but waaayyyy more primitive.

JHipster has a JDL (JHipster Domain Language) feature that allows you to model the data in your app, and generate entities from it. You can use its JDL Studio feature to do this online and save it locally once you’ve finished.

I created a data model for this app that has an Album, Photo, and Tag entities and set up relationships between them. Below is a screenshot of what it looks like in JDL Studio.

Copy the JDL below and save it in a photos.jdl file in the root directory of your project.

entity Album {
  title String required,
  description TextBlob,
  created Instant
}

entity Photo {
  title String required,
  description TextBlob,
  image ImageBlob required,
  taken Instant
}

entity Tag {
  name String required minlength(2)
}

relationship ManyToOne {
  Album{user(login)} to User,
  Photo{album(title)} to Album
}

relationship ManyToMany {
  Photo{tag(name)} to Tag{photo}
}

paginate Album with pagination
paginate Photo, Tag with infinite-scroll

You can generate entities and CRUD code (Java for Spring Boot; TypeScript and HTML for Angular) using the following command:

jhipster import-jdl photos.jdl

When prompted, type a to update existing files.

This process will create Liquibase changelog files (to create your database tables), entities, repositories, Spring MVC controllers, and all the Angular code that’s necessary to create, read, update, and delete your data objects. It’ll even generate Jest unit tests and Protractor end-to-end tests!

When the process completes, restart your app, and confirm that all your entities exist (and work) under the Entities menu.

You might notice that the entity list screen is pre-loaded with data. This is done by faker.js. To turn it off, edit src/main/resources/config/application-dev.yml, search for liquibase and set its contexts value to dev. I made this change in this example’s code and ran ./gradlew clean to clear the database.

liquibase:
  # Add 'faker' if you want the sample data to be loaded automatically
  contexts: dev

Develop a Mobile App with Ionic and Angular

Getting started with Ionic for JHipster is similar to JHipster. You simply have to install the Ionic CLI, Yeoman, the module itself, and run a command to create the app.

npm i -g [email protected] [email protected] yo
yo jhipster-ionic

If you have your app application at ~/app, you should run this command from your home directory (~). Ionic for JHipster will prompt you for the location of your backend application. Use mobile for your app’s name and app for the JHipster app’s location.

Type a when prompted to overwrite mobile/src/app/app.component.ts.

Open mobile/src/app/auth/auth.service.ts in an editor, search for data.clientId and replace it with the client ID from your Native app on Okta.

// try to get the oauth settings from the server
this.requestor.xhr({method: 'GET', url: AUTH_CONFIG_URI}).then(async (data: any) => {
  this.authConfig = {
    identity_client: '{yourClientId}',
    identity_server: data.issuer,
    redirect_url: redirectUri,
    end_session_redirect_url: logoutRedirectUri,
    scopes,
    usePkce: true
  };
  ...
}

When using Keycloak, this change is not necessary.### Add Claims to Access Token

In order to authentication successfully with your Ionic app, you have to do a bit more configuration in Okta. Since the Ionic client will only send an access token to JHipster, you need to 1) add a groups claim to the access token and 2) add a couple more claims so the user’s name will be available in JHipster.

Navigate to API > Authorization Servers, click the Authorization Servers tab and edit the default one. Click the Claims tab and Add Claim. Name it "groups" and include it in the Access Token. Set the value type to "Groups" and set the filter to be a Regex of .*. Click Create.

Add another claim, name it given_name, include it in the access token, use Expression in the value type, and set the value to user.firstName. Optionally, include it in the profile scope. Perform the same actions to create a family_name claim and use expression user.lastName.

When you are finished, your claims should look as follows.

Run the following commands to start your Ionic app.

cd mobile
ionic serve

You’ll see a screen with a sign-in button. Click on it, and you’ll be redirected to Okta to authenticate.

Now that you having log in working, you can use the entity generator to generate Ionic pages for your data model. Run the following commands (in your ~/mobile directory) to generate screens for your entities.

yo jhipster-ionic:entity album

When prompted to generate this entity from an existing one, type Y. Enter ../app as the path to your existing application. When prompted to regenerate entities and overwrite files, type Y. Enter a when asked about conflicting files.

Go back to your browser where your Ionic app is running (or restart it if you stopped it). Click on Entities on the bottom, then Albums. Click the blue + icon in the bottom corner, and add a new album.

Click the ✔️ in the top right corner to save your album. You’ll see a success message and it listed on the next screen.

Refresh your JHipster app’s album list and you’ll see it there too!

Generate code for the other entities using the following commands and the same answers as above.

yo jhipster-ionic:entity photo
yo jhipster-ionic:entity tag

Run Your Ionic App on iOS

To generate an iOS project for your Ionic application, run the following command:

ionic cordova prepare ios

When prompted to install the ios platform, type Y. When the process completes, open your project in Xcode:

open platforms/ios/MyApp.xcworkspace

You’ll need to configure code signing in the General tab, then you should be able to run your app in Simulator.

Log in to your Ionic app, tap Entities and view the list of photos.

Add a photo in the JHipster app at <a href="http://localhost:8080" target="_blank">http://localhost:8080</a>.

To see this new album in your Ionic app, pull down with your mouse to simulate the pull-to-refresh gesture on a phone. Looky there - it works!

There are some gestures you should know about on this screen. Clicking on the row will take you to a view screen where you can see the photo’s details. You can also swipe left to expose edit and delete buttons.

Run Your Ionic App on Android

Deploying your app on Android is very similar to iOS. In short:

  1. Make sure you’re using Java 8
  2. Run ionic cordova prepare android
  3. Open platforms/android in Android Studio, upgrade Gradle if prompted
  4. Set launchMode to singleTask in AndroidManifest.xml
  5. Start your app using Android Studio
  6. While your app is starting, run adb reverse tcp:8080 tcp:8080 so the emulator can talk to JHipster
Learn More About Ionic 4 and JHipster 6

Ionic is a nice way to leverage your web development skills to build mobile apps. You can do most of your development in the browser, and deploy to your device when you’re ready to test it. You can also just deploy your app as a PWA and not both to deploy it to an app store.

JHipster supports PWAs too, but I think Ionic apps look like native apps, which is a nice effect. There’s a lot more I could cover about JHipster and Ionic, but this should be enough to get you started.

You can find the source code for the application developed in this post on GitHub at @oktadeveloper/okta-ionic4-jhipster-example.

Thank you for reading!