Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
Ionic3

How to make money with Google AdMob ads in Ionic framework 3

In case you’re looking for a way to implement Google AdMob ads in Ionic framework 1, then check out this tutorial: Adding AdMob to Ionic framework application step by step.

Introduction

There are multiple ways you can earn money with your app these days and here are just a few of them:

  • Paid app – set a price for your app directly on the App/Play Store that users need to pay before downloading your app
  • Freemium – give the app for free but charge for in-app purchases like adding some extra features (think more gold or faster production in game apps)
  • Ad-based – show ads inside your application. Potentially offer the in-app purchase to remove the ads

In this post, I’m going to cover the Ad-based monetization option, and I’ll show you how to add Google AdMob ads to a simple Ionic 3 blank template application. There are two parts to implementing Google AdMob ads to an Ionic project and I broke them into: AdMob settings and Ionic settings.

Demo app and repo

You can check the final code on Github. When you clone it, run npm install inside the project. In case you have your development machine set up for Ionic, then you can run the project with ionic emulate ios or ionic emulate android. If you don’t but would like to, see this post on How to get started with Ionic framework 3 on Mac and Windows.

You should see something like this in your simulator/emulator:

AdMob settings

Let’s start with AdMob settings:

  1. Sign in/Sign up for AdMob at https://www.google.com/admob/
  2. Click the Apps and then ADD APP button:

  1. Since our app is not published yet we will click the No button:

  1. Fill in the app name and platform and click the ADD button:

  1. Save the App ID somewhere and proceed to create the Ad unit

  1. Select Banner Ad format:

  1. Configure the adds type, size, placement, style, name:

  1. You can read additional info on how to implement GA and AdMob, but for now let’s just click Done:

  1. You will now see the following similar screen:

The most important thing to note here is this Ad unit ID, which in my test case is ca-app-pub-7957971173858308/5068937357. Make a note of this string as it’s the most important part of this setting. You can click on the copy to clipboard button and paste it as a comment (for now) in your app.

  1. Create as much Ad units as you may need (for each platform[iOS, Android] and ad format [Banner, Interstitial, etc.]). In my case, I just created the additional Interstitial Ad and will use them on both iOS and Android devices for the purpose of this demo.

Ionic settings

Those of you familiar with Ionic 1 know that you can add any plugin to your Ionic project thanks to the project called ngCordova. For Ionic 3, there’s the same thing called Ionic Native.

Ionic Native is a TypeScript wrapper for Cordova/PhoneGap plugins that makes it easy to add any native functionality that you may need into your Ionic app. Ionic Native wraps the plugin callbacks in a Promise or an Observable, providing a common interface for all plugins and ensuring that native events trigger change detection in Angular.

First, let’s start an empty Ionic 3 application based on the blank template:

ionic start Ionic3AdMobTest blank --cordova

You should see the following output:

✔ Creating directory ./Ionic3AdMobTest - done!
[INFO] Fetching app base (https://github.com/ionic-team/ionic2-app-base/archive/master.tar.gz)
✔ Downloading - done!
[INFO] Fetching starter template blank (https://github.com/ionic-team/ionic2-starter-blank/archive/master.tar.gz)
✔ Downloading - done!
✔ Updating package.json with app details - done!
✔ Creating configuration file ionic.config.json - done!
[INFO] Installing dependencies may take several minutes!
> npm install
✔ Running command - done!
> npm install --save-dev --save-exact ionic@latest
✔ Running command - done!
> npm install --save-dev --save-exact @ionic/cli-plugin-ionic-angular@latest
✔ Running command - done!
> npm install --save-dev --save-exact @ionic/cli-plugin-cordova@latest
✔ Running command - done!
> npm dedupe
✔ Running command - done!
> git init
✔ Running command - done!
> git add -A
✔ Running command - done!
> git commit -m "Initial commit" --no-gpg-sign
✔ Running command - done!

♬ ♫ ♬ ♫  Your Ionic app is ready to go! ♬ ♫ ♬ ♫

Run your app in the browser (great for initial development):
  ionic serve

Run on a device or simulator:
  ionic cordova run ios

Test and share your app on a device with the Ionic View app:
  http://view.ionic.io


Next Steps:
Go to your newly created project: cd ./Ionic3AdMobTest

Navigate to the root of the application with your Terminal/Command prompt and execute the following command to add the cordova-plugin-admobpro plugin:

ionic cordova plugin add cordova-plugin-admobpro

You should see the following output after running the command:

✔ Running command - done!
Adding cordova-plugin-admobpro to package.json
Saved plugin info for "cordova-plugin-admobpro" to config.xml

Additionally, you will also need to run this command:

npm install --save @ionic-native/admob-pro

which, if completed successfully, will only output something like added 1 package in 3.331s to the console.

You need to add this second command as well because this installs some files needed by TypeScript.

⚠️ At this point, depending on the version of Ionic CLI that you have you may need to add a platform by executing: ionic cordova platform add ios or ionic cordova platform add android depending on the platform you’re trying to build for. You have to execute that if the command ionic cordova platform ls shows that you don’t have any installed platforms on the current project:

→ ionic cordova platform ls
✔ cordova platform ls - done!
Installed platforms:
Available platforms: 
 android ~6.2.2
 blackberry10 ~3.8.0 (deprecated)
 browser ~4.1.0
 ios 4.4.0
 osx ~4.0.1
 webos ~3.7.0

If everything is fine with running ionic cordova platform add ios you will see an output like this:

Using cordova-fetch for cordova-ios@~4.4.0
Adding ios project...
Creating Cordova project for the iOS platform:
    Path: platforms/ios
    Package: io.ionic.starter
    Name: MyApp
iOS project created with [email protected]
Installing "cordova-plugin-admobpro" for ios
Installing "cordova-plugin-extension" for ios
Discovered plugin "cordova-plugin-console" in config.xml. Adding it to > the project
Installing "cordova-plugin-console" for ios
Adding cordova-plugin-console to package.json
Saved plugin info for "cordova-plugin-console" to config.xml
Discovered plugin "cordova-plugin-device" in config.xml. Adding it to > the project
Installing "cordova-plugin-device" for ios
Adding cordova-plugin-device to package.json
Saved plugin info for "cordova-plugin-device" to config.xml
Discovered plugin "cordova-plugin-splashscreen" in config.xml. Adding > it to the project
Installing "cordova-plugin-splashscreen" for ios
Adding cordova-plugin-splashscreen to package.json
Saved plugin info for "cordova-plugin-splashscreen" to config.xml
Discovered plugin "cordova-plugin-statusbar" in config.xml. Adding it > to the project
Installing "cordova-plugin-statusbar" for ios
Adding cordova-plugin-statusbar to package.json
Saved plugin info for "cordova-plugin-statusbar" to config.xml
Discovered plugin "cordova-plugin-whitelist" in config.xml. Adding it > to the project
Installing "cordova-plugin-whitelist" for ios
Adding cordova-plugin-whitelist to package.json
Saved plugin info for "cordova-plugin-whitelist" to config.xml
Discovered plugin "ionic-plugin-keyboard" in config.xml. Adding it to > the project
Installing "ionic-plugin-keyboard" for ios
Adding ionic-plugin-keyboard to package.json
Saved plugin info for "ionic-plugin-keyboard" to config.xml
--save flag or autosave detected
Saving ios@~4.4.0 into config.xml file ...
✔ Copying default image resources into ./resources/ios - done!

Btw, there is also a free version of the AdMob Pro plugin. But, honestly, if you really start making money with your app, this will be a minor expense. Besides, if you’re having problems giving back to the actual plugin through which you’re making money then my dear padawan you have yet much to learn…

Now, let’s add this plugin to our app’s NgModule. In the src/app/app.module.ts file import AdmobPro:

import { AdMobPro } from '@ionic-native/admob-pro';

and then add it to the Providers array. The whole contents of the src/app/app.module.ts file should now looks like this:

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { AdMobPro } from '@ionic-native/admob-pro';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

@NgModule({
    declarations: [
        MyApp,
        HomePage
    ],
    imports: [
        BrowserModule,
        IonicModule.forRoot(MyApp)
    ],
    bootstrap: [IonicApp],
    entryComponents: [
        MyApp,
        HomePage
    ],
    providers: [
        StatusBar,
        SplashScreen,
        AdMobPro,
        { provide: ErrorHandler, useClass: IonicErrorHandler }
    ]
})
export class AppModule { }

Now I’m going to show you the final content of the src/pages/home/home.ts file and will explain what was changed step by step:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { AdMobPro } from '@ionic-native/admob-pro';
import { Platform } from 'ionic-angular';

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {
    constructor(public navCtrl: NavController, platform: Platform, private admob: AdMobPro) {
        platform.ready().then(() => {
            var admobid = {
                banner: 'ca-app-pub-7957971173858308/5068937357',
                interstitial: 'ca-app-pub-7957971173858308/5667703151'
            };

            this.admob.createBanner({
                adId: admobid.banner,
                isTesting: true,
                autoShow: true,
                position: this.admob.AD_POSITION.BOTTOM_CENTER
            })

            this.admob.prepareInterstitial({
                adId: admobid.interstitial,
                isTesting: true,
                autoShow: false
            })
        });
    }

    showInterstitialAd() {
        if (AdMobPro) {
            this.admob.showInterstitial();
        }
    }
}

First, we added the imports:

import { AdMobPro } from '@ionic-native/admob-pro';
import { Platform } from 'ionic-angular';

Then, via the constructor we injected Platform and AdMobPro:

constructor(public navCtrl: NavController, platform: Platform, private admob: AdMobPro)

Then we wrapped everything in the platform.ready() promise. This is the most important part of the code! If you wouldn’t do that, it could happen that your app would start up and the plugins would still not be properly set up, and you wouldn’t see the ads displayed.

But then again, sometimes you would, and this is what it would make it a nightmare to debug. This is a very common issue that I’ve seen even back from Ionic 1 when answering the questions on StackOverflow. So, you may want to keep an ?️ on the fact that you need to wrap any plugin calls inside the platform.ready() promise, as that way you’ll be sure that all of the plugins have loaded before you’ll use them.

The code that’s executed after the promise resolves sets up our admobid object with banner and interstitial properties. Then we’re calling the createBanner and prepareInterstitial functions on the injected admob object. Note how the banner is set to show automatically when the app loads (autoShow: true) and the interstitial isn’t. Also, note how we’ve set the position of the banner ad to the bottom:

platform.ready().then(() => {
    var admobid = {
        banner: 'ca-app-pub-7957971173858308/5068937357',
        interstitial: 'ca-app-pub-7957971173858308/5667703151'
    };

    this.admob.createBanner({
        adId: admobid.banner,
        isTesting: true,
        autoShow: true,
        position: this.admob.AD_POSITION.BOTTOM_CENTER
    })

    this.admob.prepareInterstitial({
        adId: admobid.interstitial,
        isTesting: true,
        autoShow: false
    })
});

Then we added the showshowInterstitialAdAd function, which shows the Interstitial ad:

showInterstitialAd() {
    if (AdMobPro) {
        this.admob.showInterstitial();
    }
}

Of course, at this point, change the admobid object properties to your AdMob keys which you obtained in the first part (step 9).

? If you run into any problems with this, just ping in the comments, and I’ll do my best to help you.

One common thing that you might have to do for Android is to install some extras via the Android SDK manager. To do so open Android Studio and select Configure->SDK Manager:

Make sure you have installed the packages marked as Installed on the image below (usually, those are Google Billing Library and Google Play services):

What kind of an ad should you show?

This plugin’s documentation states an interesting fact that it’s strongly recommended to use the Interstitial ad type because it brings more than 10 times profit than the banner Ad. Here’s the table from the official documentation:

Ad Format Banner Interstitial
Click Rate < 1% 3-15%
RPM (1k impressions) 0.5$ – 4$ 10-50$

Banner ad is the small add that is usually placed in the bottom of the screen, whereas Interstitial ads are full-screen ads that cover the interface of their host app. Therefore, you may rather want to opt for this kind of an ad instead for the Banner one.

It’s important to note that there’s probably no exact formula here on when to show the Interstitial Ad, but there are some best practices, and this is what Google has to say about it:

Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, like sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it’s easy to present an interstitial without disrupting their experience. Make sure you consider at which points in your app’s workflow you’ll display interstitials, and how the user is likely to respond.

You can learn a bit more about it here.

Anyways, as you saw in our demo code above, we opted for showing the banner ad all the time in the bottom of the screen, and we’re showing the interstitial ad when we click the button. You can tweak this any way you like in your app, but please remember the points mentioned above about best practices.

Finally, the view template

Replace the src/pages/home/home.html file content with this:

<ion-header>
    <ion-navbar>
        <ion-title>
            Ionic Blank
        </ion-title>
    </ion-navbar>
</ion-header>

<ion-content padding>
    <button ion-button (click)="showInterstitialAd()">Show the interstitial Ad</button>
</ion-content>

Clicking the Show the interstitial Ad button will call the showInterstitialAd() function which will show the interstitial as shown in a gif at the beginning of this tutorial.

Let’s test this

Run ionic cordova emulate ios and in a few seconds your simulator should start up and show you this:

There are few things that could go wrong with this, so for example if you get an error like this:

Error: Cannot read property 'replace' of undefined

[ERROR] Cordova encountered an error.
        You may get more insight by running the Cordova command above directly.

[ERROR] An error occurred while running cordova run ios (exit code 1).

Then you can try the solution from this StackOverflow post: Execute the following command in the platforms/ios/cordova/node_modules folder: sudo npm install ios-sim@lates.

If you get an error telling you that it can’t open up the simulator, then you may want to try running the build command: ionic cordova build ios and after that open the MyApp.xcworkspace file from the platforms/ios folder:

Select the simulator device that you’d like to run your app on and click the run button from your Xcode:

If you run into any other problems while trying to run this, let’s try to solve them in the comments and thus help others that may have the same issues as well ?

Conclusion

In this post, we’ve shown how easy it is to add monetization options to your app. Now it’s ‘just’ on you to actually make an app that will be used a lot of times and whose users will want to click on the ads. ?

Till next time, ✌️

How to make #money with Google #AdMob ads in #Ionic framework 3 https://t.co/In5UPrLTyn

— Nikola Brežnjak (@HitmanHR) August 16, 2017

Ionic3

How to create a calculator application with Ionic framework 3 by using Ionic Creator for UI

This is the second post in a series of posts which will teach you how to take advantage of your web development knowledge in building hybrid applications for iOS and Android. The first post in this series was all about How to get started with Ionic Framework 3 on Windows and Mac.

This second post explains:

  • How to create a calculator interface mockup
  • How to create a calculator interface prototype without coding by using Ionic Creator
  • How to start the Ionic 3 application based on the created interface
  • Which are the most important folders and files and what is the starting point of the Ionic 3 application
  • How to create the calculator logic

Finished project:

  • clone the code from Github
  • in the project directory execute ionic lab to run the project locally in your browser
  • you can check out the live example of this application or view this gif:

Introduction

Since there are not so many Calculator applications in the App Store, who knows, you just may create a bestseller in this category, if you add a needed tweak or two.

All jokes and hopes aside; this seemed to be decent, but still easy to accomplish task. Let’s start this chapter by creating the interface for our application.

Calculator interface mockup

Before starting any application, we should know what we want (well, at least in general). We should know what problem are we trying to solve with our application and how are we going to solve it. Also, we should have a decent idea of how we would want our application to look like.

The answers to the first two questions would be rather easy; the problem is that we can’t do calculations fast enough in our mind (well, except if you’re Arthur Benjamin) and we need a tool to help us with that. Surely, there are specific calculator devices, but it would be too cumbersome to carry one with us all the time.

Besides, since these days almost everyone has a smartphone, it turns out it would be an awesome idea to make an app for it. Because, as they say:

there’s an app for that

Where that is basically everything these days. If you find that there isn’t an app for some particular problem that you may have, that just may be your lucky break. Who knows, you just may end up having your 5 minutes of fame on the AppStore, until another clone of your app pushes you away.

Anyways, back to our calculator application; we don’t need any fancy options (at least not yet, in this 1.0 version), we’ll just stick with the basic mathematical operations like adding, subtracting, dividing and multiplying.

These basic operations will be our MVP (Minimum Viable Product), as the author Eric Ries explains in his awesome (and highly recommended) book Lean Startup. We can always add features later if it turns out that our idea was good. Or, we can pivot away from it, if it turns out it was not a next best thing after Flappy Bird. That way, we wouldn’t spend too much time and money building the app with a dozen features which, in the end, would not be used at all.

As for the user interface, you can use various tools that help with mocking up your application’s user interface (Balsamiq Mockups, Mockingbird, Mockup Builder). I tend to be old school about it, and I made a little hand drawing of how I imagined the app should look like, and this is what I came up with after few attempts:

Calculator interface prototype

Now that we know what our application needs to do and how it has to look like, let’s start by creating our interface.

We could create our interface by manually coding it in HTML/CSS, but we’re going to show a different approach here – the one which uses Ionic Creator, which is an awesome web application (soon to be a desktop app as well) that lets you drag&drop components that make up the user interface. As such, this is a great tool which helps in quick user interface prototyping.

The best thing is that you can then just download the created HTML/CSS (just recently they’ve added Ionic 3 support) and use it directly in your Ionic application. Of course, some additional changes will be needed later in the HTML and CSS code, but for creating a quick prototype, this will be more than enough.

Worth noting is that there are currently on the market lots of other tools for interface prototyping (InVision, Flinto, Figma 2.0). However, these tools don’t (at least not yet) have a “one-click download and ready for Ionic” option like Ionic Creator does.

Creating calculator interface with Ionic Creator

To use Ionic Creator you have to signup/login on their website. They are currently offering a 14-day trial (no credit card needed to sign up) of Creator Pro which is their best plan and has the following features:

On the initial screen, click the New Project button and fill out project’s name, type and Ionic version:

Please note that Ionic 3 code export is in Alpha mode currently – this will change in the coming months

The main screen of the Ionic Creator application looks like this:

In the upper left-hand side you’ll see the Pages panel, and inside it, you’ll see the Page item. Click on Page, and on the right-hand side change the Title to Calculator. Next, disable the Padding option by switching off the Padding checkbox under the Miscellaneous section on the right-hand side. The way this should look like now is shown on the image below:

First, we need some kind of a “display” which will show the numbers that we’re clicking. Ideally, we would use a <label> component, however, it’s not available in the Ionic Creator as of yet. So, for this, we will use the <input> element, and we can easily adjust this later when we download the generated HTML code.

Ionic Creator works in a drag&drop kind of way, which basically means that you can drag any component from the Components pane on the left-hand side and drop it on the Phone image in the center of the screen.

Since we concluded that we’d use the Input element, just drag&drop it to the Phone.

Select the Input component (by clicking on it in the Pages panel in the upper left corner mentioned before) and:

  • change Placeholder to 0 (zero digit)
  • change Name to display
  • remove the text under Title

The way this should look like now is shown on the image below:

Next, according to our mockup, we should add buttons that would represent the following:

  • digits from 0 to 9
  • adding (+)
  • substracting (–)
  • multiplying (x)
  • dividing (/)
  • modulo (%) – we are, after all, programmers, right? ?‍? ?

Also, we would need an equals button (=), a clear button (C) and a floating point (.) button.

In the first row we need to have three buttons, the ones representing the Clear operation (C), modulo operation (%) and divide operation (/). To accomplish this, we will use a Button component from the Components panel and drag&drop it just below the Input field on the screen. But, before you do that, you have to drag&drop the Container component as we will drop these operation buttons into it.

So, to sum up:
+ first, drag&drop the Container component, and then
+ drag&drop the Button component to the phone image inside the Container component

When done, change the Button’s Width property under the Style section on the right-hand side to Inline and color to Energized. Now, either repeat the process two more times or click on the duplicate icon which appears on the Button component once selected (just left of the x icon). Then change the Text of the buttons to C, % and / respectively. You should see something like this now in your Ionic Creator window:

Don’t worry that this now doesn’t look like in our design; we will deal with this at a later stage.

Those of you familiar with Ionic 1 (also covered in my previous book) know that we had the useful Button Bar component which doesn’t exist in Creator now, but we still have few options.

Now, repeat the process for the second row by first adding another Container component below the previous one and then adding four buttons: 7, 8, 9 and x into it. The additional change on the number buttons is that you need to set their color to Positive (TBH, ‘Positive` is the default color, so you basically won’t have to change anything).

Now you need to repeat the process by adding next three rows. The best thing you can do to speed up the process is to duplicate the whole row by clicking the duplicate icon:

and then change the button text to represent all the missing buttons per rows:

  • buttons representing 4, 5, 6 and a button representing subtraction (–)
  • buttons representing 1, 2, 3 and a button representing addition (+)

Number buttons should have a Positive style, and operation buttons should have an Energized style.

In the last row you should add three buttons (just delete one after you duplicate the whole row of four buttons):

  • one button representing 0, with the Positive style
  • one button representing floating point (.)
  • one button representing the Equals operation (=), with the Assertive style

Your interface should now look like this:

Don’t worry about the slight misalignment or padding; we’ll take care of this in the next chapter when we’ll be polishing our application and preparing it for the App/Play store.

So, this is it, we have our interface ready, and now we can export it by clicking on the Export icon in the header, as shown in the image below:

After this a popup, with the following content, appears:

Click the Download project ZIP button and save it to your computer.

Starting a project with Ionic CLI by using the template made in Ionic Creator

First, unzip the file that you’ve downloaded in the previous step. Then, start a new Ionic app by executing the following command in your Terminal:

ionic start Ionic3_2ndTutorial blank

Now go into the newly created Ionic3_2ndTutorial directory, and overwrite the src folder with the contents from your zip export. You will want to overwrite the app directory, pages directory, and index.html file.

Note: you’re free to name your project any way you want, I chose Ionic3_2ndTutorial in this example, and I used the ‘blank’ template.

Now, let’s see this in action; execute ionic lab and you should get an output like this:

[INFO] Starting app-scripts server: --lab --l --port 8100 --p 8100 --livereload-port 35729 --r 35729 --address 0.0.0.0 -
       Ctrl+C to cancel
[09:39:31]  watch started ... 
[09:39:31]  build dev started ... 
[09:39:31]  clean started ... 
[09:39:31]  clean finished in less than 1 ms 
[09:39:31]  copy started ... 
[09:39:31]  transpile started ... 
[09:39:33]  transpile finished in 1.83 s 
[09:39:33]  preprocess started ... 
[09:39:33]  deeplinks started ... 
[09:39:33]  deeplinks finished in 6 ms 
[09:39:33]  preprocess finished in 7 ms 
[09:39:33]  webpack started ... 
[09:39:33]  copy finished in 1.98 s 
[09:39:38]  webpack finished in 5.41 s 
[09:39:38]  sass started ... 
[09:39:39]  sass finished in 1.02 s 
[09:39:39]  postprocess started ... 
[09:39:39]  postprocess finished in 9 ms 
[09:39:39]  lint started ... 
[09:39:39]  build dev finished in 8.32 s 
[09:39:39]  watch ready in 8.36 s 
[09:39:39]  dev server running: http://localhost:8100/ 

[INFO] Development server running
       Local: http://localhost:8100

[09:39:42]  lint finished in 2.32 s

In the first tutorial we used the ionic serve command which starts up a local web browser and shows how our application would look like. This one is similar but in a way better as it can nicely show us how our app would look like on different platforms:

You can still use the ionic serve command if you like. The live preview is great for rapid development since you get to see changes instantly without needing to reload your browser manually.

If you get an error similar to this:
Error: tsconfig: Cannot read file '/DEV/Ionic3_2ndTutorial/src/tsconfig.json': ENOENT: no such file or directory, open '/DEV/Ionic3_2ndTutorial/src/tsconfig.json'.
then you didn’t run the ionic lab command in the project directory and so you should first cd into that directory (as mentioned in the previous step) and then run the ionic lab command.

Now, let’s go and see what our generated folder structure looks like and what is each folder responsible for.

Ionic application folder structure

If you open up the project in your editor (I’m using Visual Studio Code), you will see something like:

Now we’re going to explain what each of these files and folders represents in Ionic framework 3.

hooks folder

hooks folder contains code for Cordova hooks, which are used to execute some code during the Cordova build process. For example, Ionic uses Cordova’s after_prepare hook to inject platform specific (iOS, Android, Windows Phone) CSS and HTML code.

node_modules folder

node_modules folder contains all the Node modules that Ionic CLI uses in the background like for example babel, browserify, lodash, uglify, webpack to name just a few. There are 550+ tools in that folder ?, and you shouldn’t worry about it at this point at all.

resources folder

resources folder contains two files (icon.png and splash.png) and two folders (android and ios) which contain all the needed icon and splash screen sizes. Ionic has a simple command which creates all the icon and splash screen sizes for you automatically. We will cover that in more detail in the next tutorial.

src folder

src folder is the most important since it contains all the files our application is made of, and we will be spending most of our development time in this folder. This folder contains few files and additional sub folders which we’ll address in more detail in the next section titled Refactoring our application.

www folder

www folder contains the optimized version of our application (minimized, compressed, etc.). In future tutorials, we’ll show how easy it is to just take the contents of this folder and put it on your web server, and you would have the application ready and running. If you take a look at the live example of this project, this is exactly what I did.

.editorconfig file

.editorconfig is a configuration file for Visual Studio Code.

config.xml file

config.xml is a configuration file for the Cordova project (as you may remember from the first tutorial, Ionic is built on top of Cordova). It contains some meta information about the app like permissions and a list of Cordova plugins which are used in the app. To learn more about available settings in the config.xml file, please refer to the official documentation.

ionic.config.json file

ionic.config.json is a configuration file for Ionic, used to store meta information about an Ionic project and the associated Ionic.io cloud account. We’re not going to use Ionic.io cloud account just yet, we’ll show how to use it in the next chapter.

The contents of my ionic.config.json file is as follows:

{
  "name": "Ionic3_2ndTutorial",
  "app_id": "",
  "type": "ionic-angular"
}

It defines the name of the app and its type, along with the app_id in case you’ve created the Cloud account for this project (if you’ve answered Yes to the question when starting the project).

package.json file

package.json is a file used by npm to store versions of the npm packages installed in the current project.

npm (Node.js Package Manager) is a CLI tool which comes with Node.js installation and it’s used for installing other tools like aforementioned Browserify, Babel, etc…

Contents of my package.json file, shown below, is useful as we can see which Cordova plugins and dependencies we have installed on the project, as well as some meta information like name, version and description:

{
  "name": "Ionic3_2ndTutorial",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.1.3",
    "@angular/compiler": "4.1.3",
    "@angular/compiler-cli": "4.1.3",
    "@angular/core": "4.1.3",
    "@angular/forms": "4.1.3",
    "@angular/http": "4.1.3",
    "@angular/platform-browser": "4.1.3",
    "@angular/platform-browser-dynamic": "4.1.3",
    "@ionic-native/core": "3.12.1",
    "@ionic-native/splash-screen": "3.12.1",
    "@ionic-native/status-bar": "3.12.1",
    "@ionic/storage": "2.0.1",
    "ionic-angular": "3.5.3",
    "ionicons": "3.0.0",
    "rxjs": "5.4.0",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.12"
  },
  "devDependencies": {
    "@ionic/app-scripts": "2.0.2",
    "@ionic/cli-plugin-ionic-angular": "1.3.2",
    "typescript": "2.3.4"
  },
  "description": "An Ionic project"
}

package-lock.json file

package-lock.json file is automatically generated for any operation where npm modifies either the node_modules folder or package.json file. It describes the exact folder contents that was generated so that future installs can generate identical folder contents, regardless of intermediate dependency updates. This file is intended to be committed into source repositories so that your teammates (or continuous integration systems, if you have those set up) are guaranteed to install exactly the same dependencies.

.gitignore and README.md file

Both .gitignore and README.md are files related to GitHub.

I’m sure most of the readers know and use GitHub (and consequently Git), but just for brevity, let see how Wikipedia defines GitHub:

GitHub is a Web-based Git repository hosting service, which offers all of the distributed revision control and source code management (SCM) functionality of Git as well as adding its own features. Unlike Git, which is strictly a command-line tool, GitHub provides a Web-based graphical interface and desktop as well as mobile integration. It also provides access control and several collaboration features such as bug tracking, feature requests, task management, and wikis for every project.

So, Git on the other hand is (quoted from the official site):

a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. Git is easy to learn and has a tiny footprint with lightning fast performance. It outclasses SCM tools like Subversion, CVS, Perforce, and ClearCase with features like cheap local branching, convenient staging areas, and multiple workflows.

If you’re not using Git (and Github) in your workflow, I highly encourage you to do so, as it will prove really useful in the long run.

Now that we got the basics out of the way let’s take a look at what the files above represent.

.gitignore is a configuration file for GitHub. Contents of the .gitignore file, shown below, basically instructs Git which folders it shouldn’t track and upload to GitHub.

# Specifies intentionally untracked files to ignore when using Git
# http://git-scm.com/docs/gitignore

*~
*.sw[mnpcod]
*.log
*.tmp
*.tmp.*
log.txt
*.sublime-project
*.sublime-workspace
.vscode/
npm-debug.log*

.idea/
.sass-cache/
.tmp/
.versions/
coverage/
dist/
node_modules/
tmp/
temp/
hooks/
platforms/
plugins/
plugins/android.json
plugins/ios.json
www/
$RECYCLE.BIN/

.DS_Store
Thumbs.db
UserInterfaceState.xcuserstate

README.md is a Markdown file used on GitHub to document the purpose and usage of your project. In general, IMHO, every project should have a decently written README.md file which explains the basic usage of the project along with instructions on how to run it, contribute to it, etc.

tsconfig.json file

tsconfig.json is TypeScript configuration file. We won’t go into the details here, but I encourage you to take a look at the official documentation.

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5"
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}

tslint.json file

tslint.json is TypeScript Linter configuration file. Linter is a program which checks TypeScript code for readability, maintainability, and functionality errors. For more info, and to learn what the contents of the file shown below represents, please check the official docs.

{
  "rules": {
    "no-duplicate-variable": true,
    "no-unused-variable": [
      true
    ]
  },
  "rulesDirectory": [
    "node_modules/tslint-eslint-rules/dist/rules"
  ]
}

Refactoring our application

As said, we’ll be spending most of our development time in the src folder, and that’s why we mentioned it just briefly in the previous section. We’ll take a full deep dive into it here, by explaining each file (that we’ll change) in detail.

Finally, we’ll add the calculator logic so that our calculator will work as expected.

Generally, putting all the code in one file and mixing logic and presentation (JavaScript and HTML code) is simply a big NO-NO, and often referred to as spaghetti code. You can learn more about refactoring your code from the cult book Refactoring: Improving the Design of Existing Code by Martin Fowler, Kent Beck, and others. If you’re searching for a bit lighter introduction to refactoring and good programing practices, in general, I can’t recommend the classic Code Complete 2 by Steve McConnell enough. I’ve read the book way back in 2011, and you can read my notes from the first part of the book here.

^ This was the comment from the first edition of this book (covering Ionic 1). I am happy to report that ever since Ionic has done an awesome job in separating the logic and presentation into components. Mainly this benefit comes from Angular (currently at version 4.x).

index.html file

The starting point of our Ionic application is index.html, whose contents is as follows:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8">
  <title>Ionic3Calculator</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">

  <!-- cordova.js required for cordova apps -->
  <script src="cordova.js"></script>

  <!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.log('Error', err));
    }
  </script>-->

  <link href="build/main.css" rel="stylesheet">

</head>
<body>

  <!-- Ionic's root component and where the app will load -->
  <ion-app></ion-app>

  <!-- The polyfills js is generated during the build process -->
  <script src="build/polyfills.js"></script>

  <!-- The vendor js is generated during the build process
       It contains all of the dependencies in node_modules -->
  <script src="build/vendor.js"></script>

  <!-- The bundle js is generated during the build process -->
  <script src="build/main.js"></script>

</body>
</html>

I’m expecting that you have a decent understanding of HTML, so I won’t explain every HTML tag.

In the index.html file we’re loading in the CSS and JS files from the build folder. The most important tag is <ion-app></ion-app> since this is where we’ll be loading our application.

app folder

The app folder with the src folder is the starting point of every Ionic3 application.

app.components.ts file

Here I won’t go into too much detail (as this post is long enough on its own now ?) but I want to show you where your page is being loaded in. The contents of the file should be as follows:

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { CalculatorPage } from '../pages/calculator/calculator';

@Component({
    templateUrl: 'app.html'
})

export class MyApp {
    rootPage: any = CalculatorPage;

    constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
        platform.ready().then(() => {
            // Okay, so the platform is ready and our plugins are available.
            // Here you can do any higher level native things you might need.
            statusBar.styleDefault();
            splashScreen.hide();
        });
    }
}

The important line here is rootPage: any = CalculatorPage; which sets the root page of your app to the CalculatorPage, which again is imported at the beginning of the file:

import { CalculatorPage } from '../pages/calculator/calculator';.

platform.ready event is triggered after the device (your mobile phone on which the application is started) is all set up and ready to use. This includes plugins which are used in this project. If you would try to check if some plugin is available outside of the ready function callback, you could get wrong results because it is possible that some plugin would not have been set up just yet. You can learn more about Ionic Platform utility methods here.

Important to note are the places in code where and how the same CalculatorPage is injected in the app.module.ts file and added in the @NgModule declarations and entryComponents.

In this app folder, in the file app.scss you could put some style rules that you want to apply globally for your application. We’ll cover styling in the next tutorial where we’ll polish our existing calculator application.

cordova.js, manifest.json and service-worker.json files

We won’t be dealing with these three files in this tutorial. We’ll leave them for another tutorial in which we’ll explain how to create a PWA (Progressive Web App) with Ionic and how to use native plugins (accessing Camera, etc.).

Calculator logic with controllers

Ionic Creator has nicely generated a calculator page for us in the pages folder:

As mentioned before, the organization like this is so much better from what we had before as now we have three files per each component:

  • HTML template file (calculator.html)
  • SASS file (calculator.scss)
  • TypeScript file (calculator.ts)

This way we have the presentation (HTML + CSS) and logic (TS) separated and this is something you should always strive for.

Ionic Creator generated the following code for our calculator.ts file:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
    selector: 'page-calculator',
    templateUrl: 'calculator.html'
})
export class CalculatorPage {
    constructor(public navCtrl: NavController) {

    }
}

This is a bare bones code template where we’re importing the Component and NavController components; then we’re defining our Component decorator selector and templateUrl. Finally, we’re exporting the CalculatorPage class and defining the constructor inside it.

The templateUrl defines the location of the HTML template, and the selector defines the HTML tag (<page-calculator></page-calculator>) that will be used in our template once the app is generated:

Here we’re going to add the small piece of code which will make our app justWork™. Just add this code in the CalculatorPage class:

result = '';

btnClicked(btn) {
    if (btn == 'C') {
        this.result = '';
    }
    else if (btn == '=') {
        this.result = eval(this.result);
    }
    else {
        this.result += btn;
    }
}

In this code, we’re defining a variable result, so that we can show it in our template file (calculator.html).

Next, we defined a new function called btnClicked which accepts one parameter named btn. Inside the function, we’re checking for the passed parameter, and we have three cases based on the value of the parameter that is passed:

  • if the parameter equals C then we’re clearing the result
  • if the parameter equals = then we’re calculating the equation and showing the result
  • in any other case we’re just appending the button’s value to the current equation

Please note that because of brevity we haven’t added any additional checks like if someone accidentally (or intentionally) clicks two times on a button which represents some operation. We will “fix” this in the next chapter when we’ll be polishing the application. Also, you may have read on the Internet that using eval is wrong or just bad. True, it can be bad if used to evaluate some other user input, but in this case, we’ll be fine.

Finishing the calculator template

The only thing which is left for us to do is to add the appropriate function calls on the buttons in the calculator.html template. All that we have to do is add the (click)="btnClicked() function call to each button, and pass in the appropriate parameter. The template that Ionic Creator created for us looks like this:

<ion-header>
    <ion-navbar>
        <ion-title>
            Calculator
        </ion-title>
    </ion-navbar>
</ion-header>

<ion-content id="page1">
    <form id="calculator-form1">
        <ion-item id="calculator-input1">
            <ion-label></ion-label>
            <ion-input type="text" placeholder="0" name="display"></ion-input>
        </ion-item>
    </form>

    <div id="calculator-container3">
        <button id="calculator-button1" ion-button color="energized"> C </button>
        <button id="calculator-button2" ion-button color="energized"> % </button>
        <button id="calculator-button3" ion-button color="energized"> / </button>
    </div>

    <div id="calculator-container6">
        <button id="calculator-button10" ion-button color="positive"> 7 </button>
        <button id="calculator-button11" ion-button color="positive"> 8 </button>
        <button id="calculator-button12" ion-button color="positive"> 9 </button>
        <button id="calculator-button13" ion-button color="energized"> x </button>
    </div>

    <div id="calculator-container7">
        <button id="calculator-button14" ion-button color="positive"> 4 </button>
        <button id="calculator-button15" ion-button color="positive"> 5 </button>
        <button id="calculator-button16" ion-button color="positive"> 6 </button>
        <button id="calculator-button17" ion-button color="energized"> - </button>
    </div>

    <div id="calculator-container8">
        <button id="calculator-button18" ion-button color="positive"> 1 </button>
        <button id="calculator-button19" ion-button color="positive"> 2 </button>
        <button id="calculator-button20" ion-button color="positive"> 3 </button>
        <button id="calculator-button21" ion-button color="energized"> + </button>
    </div>

    <div id="calculator-container9">
        <button id="calculator-button22" ion-button color="positive"> 0 </button>
        <button id="calculator-button23" ion-button color="positive"> , </button>
        <button id="calculator-button25" ion-button color="energized"> = </button>
    </div>
</ion-content>

I have to note that in the current version of Ionic Creator export they still have the old names for colors and we will have to change this. The old Ionic 1 style colors were this:

$light:                           #fff !default;
$stable:                          #f8f8f8 !default;
$positive:                        #387ef5 !default;
$calm:                            #11c1f3 !default;
$balanced:                        #33cd5f !default;
$energized:                       #ffc900 !default;
$assertive:                       #ef473a !default;
$royal:                           #886aea !default;
$dark:                            #444 !default;

The new color names are now these (defined in the src/theme/variables.scss file):

$colors: (
    primary:    #488aff,
    secondary:  #32db64,
    danger:     #f53d3d,
    light:      #f4f4f4,
    dark:       #222,
    energized: #ffc900;
);

In our template, where we have color="positive" we can just delete that as that is now the default color if no color is defined on the button.

So, we won’t change the existing names, as then we would break the code for where this particular variable name is used. We will just add our own class for energized so that the new colors array will look like this:

$colors: (
    primary:    #488aff,
    secondary:  #32db64,
    danger:     #f53d3d,
    light:      #f4f4f4,
    dark:       #222,
    energized: #ffc900
);

Additionally, somewhat a departure from the design, we will add the danger color to the buttons C and =.

This is how the template should look like now:

<ion-header>
    <ion-navbar>
        <ion-title>
            Calculator
        </ion-title>
    </ion-navbar>
</ion-header>

<ion-content id="page1">
    <form id="calculator-form1">
        <ion-item id="calculator-input1">
            <ion-label></ion-label>
            <ion-input type="text" placeholder="0" name="display" [(ngModel)]="result"></ion-input>
        </ion-item>
    </form>

    <div id="calculator-container3">
        <button id="calculator-button1" ion-button color="danger" (click)="btnClicked('C')"> C </button>
        <button id="calculator-button2" ion-button color="energized" (click)="btnClicked('%')"> % </button>
        <button id="calculator-button3" ion-button color="energized" (click)="btnClicked('/')"> / </button>
    </div>

    <div id="calculator-container6">
        <button id="calculator-button10" ion-button (click)="btnClicked('7')"> 7 </button>
        <button id="calculator-button11" ion-button (click)="btnClicked('8')"> 8 </button>
        <button id="calculator-button12" ion-button (click)="btnClicked('9')"> 9 </button>
        <button id="calculator-button13" ion-button color="energized" (click)="btnClicked('*')"> * </button>
    </div>

    <div id="calculator-container7">
        <button id="calculator-button14" ion-button (click)="btnClicked('4')"> 4 </button>
        <button id="calculator-button15" ion-button (click)="btnClicked('5')"> 5 </button>
        <button id="calculator-button16" ion-button (click)="btnClicked('6')"> 6 </button>
        <button id="calculator-button17" ion-button color="energized" (click)="btnClicked('-')"> - </button>
    </div>

    <div id="calculator-container8">
        <button id="calculator-button18" ion-button (click)="btnClicked('1')"> 1 </button>
        <button id="calculator-button19" ion-button (click)="btnClicked('2')"> 2 </button>
        <button id="calculator-button20" ion-button (click)="btnClicked('3')"> 3 </button>
        <button id="calculator-button21" ion-button color="energized" (click)="btnClicked('+')"> + </button>
    </div>

    <div id="calculator-container9">
        <button id="calculator-button22" ion-button (click)="btnClicked('0')"> 0 </button>
        <button id="calculator-button23" ion-button (click)="btnClicked('.')"> . </button>
        <button id="calculator-button25" ion-button color="danger" (click)="btnClicked('=')"> = </button>
    </div>
</ion-content>

As you can see from the code, we’re passing to the function an argument which represents the clicked button.

Also, worth noting is that we used the

[(ngModel)]="result"

on the input element, so that we can access it from the controller through the Angular two-way binding and that we can enter some formula in the input field ourselves as well.

We could have used just the one-way binding like this:

[ngModel]="result"

but if we manually entered something in the input field, it would not ‘propagate’ to our code.

Run the application

Now you can run the application by executing the command

ionic lab

and you should see your awesome calculator open up in your browser:

as noted before, don’t worry this doesn’t look ‘slick’ or that it doesn’t ‘pop’ (or some other nonsense word the ‘knowledgeable’ people use these days), we’ll take care of this in the following tutorial.

The best thing, it should ? also work as expected. So, if you try to enter something like 2+3-10*2 and tap on = you should get the expected -15 (yes, operator precedence is taking place correctly).

We also have the floating point arithmetic like 2.3+3.2 equals 5.5.

As mentioned at the beginning of this chapter, you can take a look at the source code on GitHub, or you can take a look at the live example of this application.

Conclusion

In this chapter, we covered how to create a calculator application step by step. We showed how to create a mockup of our idea; then we showed how to create an interface by using Ionic Creator, and finally how to implement calculator’s logic.

In the next chapter, we’re going to take a look at how to test our application on the real physical devices, and how to use Ionic View App to share our application with other users without going through the app store. Also, we’re going to take a look at how to implement Google Analytics and Google Admob ads, and how to prepare our application for the stores. Additionally, we’ll take a look at how to customize the icons and the application’s splash screen.

Until next time, keep on improving ?

How to create a #calculator application with @Ionicframework 3 by using #Ionic Creator for UI https://t.co/ElzEhU8Jrc

— Nikola Brežnjak (@HitmanHR) August 2, 2017

Ionic3

How to get started with Ionic framework 3 on Mac and Windows

This is the first post in a series of posts which will teach you how to take advantage of your web development knowledge in building hybrid applications for iOS and Android with Ionic framework 3 (I’ll use Ionic in the rest of the post).

This is an update of the series of posts that I did for the original version of the Ionic framework, and you can read it here.

This first post explains:

  • How to make an app these days
  • What actually is Ionic framework
  • How is Ionic 3 different from Ionic 1 and 2
  • How to install Ionic on both Mac and Windows
  • How to use Ionic CLI to start an Ionic project
  • How to run an Ionic application

You can read the second post in the series here: How to create a calculator application with Ionic framework 3 by using Ionic Creator for UI.

Why should you listen to me?

This is in no way my attempt at feeding my ego, it’s just to give you soundness of mind that what I’m writing here may actually be useful to you.

  • Wrote a book about the original Ionic framework, and you can get it for free
  • Wrote for Pluralsight on the topic of Ionic: Ionic Framework: A definitive 10,000-word guide
  • In the top #3 all time answerers for the ionic tag on StackOverflow. If you want to see what those answers actually are, you can take a look at my StackOverflow profile.
  • Was a technical reviewer for the book Getting started with Ionic

Introduction

…up to 90% of mobile time is spent in apps

You’re bombarded with reports like this and this that users tend to spend way more time on their phones and especially in apps (rather than surfing the web using their phones) and you decided that it’s time to learn how to make an app.

If you’re a web developer, you have a decent knowledge of HTML, CSS, and JavaScript; also, you’re most likely using one of the ever so slightly popular frameworks these days like Angular, React or Ember, to name a few. If you’re even proficient enough with the MEAN stack, you are a well-rounded full stack developer, and you basically have it all. Well, except the apps part, right?

If you want to see what’s all that fuss about the MEAN stack, you can check out the free four-part tutorial series that I wrote for HackHands, starting with the first post on How to get started on the MEAN stack.

But, where to start with making an app? Could you use some of your existing skills? Up until fairly recently, if you wanted to make an app for (currently) two most popular mobile operating systems (iOS and Android – sorry Windows Phone ?) your only bet was to make the so-called, native application by using the SDKs of the intended platforms.

This, of course, meant that you needed to make two versions of your application; one for iOS and one for Android. If you are a solo developer, chances that you’re proficient in both are not so great. Even if you are; I bet you’re favoring one platform over the other, right?

Therefore, for some time, developers were opting for either iOS or Android, whereas big firms had two developing departments, one for each platform.

Nowadays, luckily, with the help of Ionic Framework, and few others like React Native, NativeScript, Fuse, you can create an application by using the skills you, as a web developer, already have. If you’re not a web developer, don’t fret – this isn’t rocket science or machine learning… ?

How can you make an app these days?

We’ve kind of touched all three in the Introduction section, but let’s keep it nice and concise and list them here as well. So, there are actually few ways that you can make an application for mobile devices these days:

  • Native app
  • Mobile website (PWA)
  • Hybrid app
  • Xamarin, ReactNative, NativeScript!?

Now, let’s talk a bit more about the pros and cons of each of them.

Native app

As mentioned previously, you can make an app specifically for iOS and Android by using their specific SDKs. If you want to build a native application for iOS you have to:

  • have a Mac computer. Sure, there are ways around it, but I honestly don’t recommend them; for starters, a cheap Mac Mini will do just fine
  • download Xcode from the App Store (it’s actually free)
  • buy the Apple Developer license that costs 99$ per year. Even if you don’t make any new apps after publishing your one app to the App Store, you’ll still have to renew your subscription every year to keep your app in the App Store ??

You can write the apps by using the Swift language, or it’s predecessor ObjectiveC.

If we’re honest here, I think that Swift is a great step up from the clunky ObjectiveC, but that’s just my own opinion (some people, of course, disagree). Anyways, if you ever decide to go native just make sure you go with Swift as you’ll get to know your way around it way sooner than with ObjectiveC, especially if you have a background in web development.

If you want to build a native application for Android you have to:

  • have any computer
  • download the appropriate SDKs (we’ll cover this in the next section)
  • buy the Google Developer license which is a one time 25$ purchase

One of the pros of a native applications would be it’s speed and direct access to a native API (you don’t have to use any middleman wrappers, like in hybrid apps). A definite con of a native applications is that you need to build two (or more) applications, one for each desired platform.

Mobile website (PWA)

A mobile website is actually a “normal” website (yeah, don’t go jumping because of the terminology; you’re smart, you get the point) that you visit with your browser on your phone, designed specifically to adapt to your phone’s screen. As we’ve noted in the Introduction section, researches show that in today’s world mobile websites tend to have a way lower engagement than they used to.

Developers used to make specific sites just for mobile browsers (on it’s own domain; usually m.domain.com) but this proved to be hard to maintain. A practice called responsive website design is used these days, where you basically have one HTML codebase, and you determine the look for specific devices (based on resolutions) by using the so-called media queries.

A great example of a mobile framework is jQuery mobile that is soon coming out with its new 1.5 version (here’s their alpha changelog), so we’ll see if they bring something new to the table. From my personal experience with the framework from four years ago, I have all but good words for it; so, definitely use it if you’re “only” making a mobile version of your web application.

A definite advantage of the mobile websites is that you can update them as you see fit, without waiting for the approval from Apple or Google. One of the disadvantages is definitely the fact that the mobile websites these days have way lower engagement than they used to, and that you can’t basically use any of the additional phone features like for example camera or GPS.

Since this is an update of the post, few things have changed and if you only want to make a ‘mobile website’. I’d suggest looking into PWA (Progressive Web Apps) as they are the new cool nowadays, and some go even as far as saying that native apps are doomed due to PWAs, but we won’t be focusing on that here.

Good news for those of you who also want to create PWAs of your apps – with Ionic you can! Ionic enables you to get the best of both worlds: cross-platform app store deployment on iOS, Android, and Windows, along with deployment to the mobile web as a Progressive Web App with the same code. But, let’s not be hasty, we’ll cover that in the next section.

Hybrid app

A hybrid app is a basically a mobile application, written with the same set of languages that you use when building websites, with the addition that it contains an isolated browser instance, called WebView, which runs this web application inside of a native app. Hybrid apps can access the mobile device and use the additional phone features like for example camera or GPS.

A definite advantage of the hybrid apps is the fact that you can access the additional phone features via plugins and that you can do all the development with the same set of skills as you use when developing “normal” web applications.

One of the disadvantages is the fact that, even though it’s improving, the so-called Web View has its limitations in terms of speed. Also, it might not be best suited to choose hybrid if you’re using a lot of additional phone features, as you would have to use a lot of plugins which would slow the app down. But, from my personal experience, we have 30+ plugins (yeah, don’t ask) that we use in our app and we’re getting away with it ?.

Finally, you would definitely not use it if you’re on a quest to make the next best game with full-blown 3D graphics.

Xamarin, ReactNative, NativeScript!?

We have to be fair here and mention the new players who promise the fact of having a full API access without any additional plugins and produce ‘actual’ native apps with very high percentage of shared code. So, the app is not run in the Web View like in Ionic’s case which is a boost to the app speed.

If you’re coming from .NET background and you want to create an app; then you can stop reading here, as from what I’ve seen Xamarin is a sure bet for you and you’ll instantly feel at home.

If you’re a React guy, then ReactNative may just be up your alley. As they say on their website:

With React Native, you don’t build a “mobile web app”, an “HTML5 app”, or a “hybrid app”. You build a real mobile app that’s indistinguishable from an app built using Objective-C or Java. React Native uses the same fundamental UI building blocks as regular iOS and Android apps. You just put those building blocks together using JavaScript and React.

As for NativeScript; to be honest, I don’t have experience with it, but it seems they’re in a similar boat as ReactNative as they also give you the NativeUI without web views.

You can check out a good blog post on the topic of Ionic vs. NativeScript vs. ReactNative here.

What is Ionic and why it’s so good

As I gave an answer on StackOverflow:

Disclaimer: This will sound like an advertisement, so I have to say I’m in no way affiliated with Ionic, I just happen to like it so much that I’m sharing the love for it.

Ionic is so much more than “just” a UI framework. Ionic allows you to:

  • have truly only one single codebase and deploy to iOS, Android, and Windows, along with the mobile web as a Progressive Web App
  • generate icons and splash screens for all devices and device sizes with a single command: ionic cordova resources. This alone saves you at least a day of image preparing for various sizes.
  • instantly update your apps with code changes, even when running directly on your device with ionic cordova run --livereload
  • build and test iOS and Android versions side-by-side and see changes instantly with ionic lab
  • share your Ionic apps with clients, customers, and testers all around the world without ever going through the App Store with ionic upload
  • easily access the full native functionality of the device using Ionic Native
  • Also, Drifty (the team behind the Ionic framework) is building a full-stack backend services and tools for your Ionic app like Live updating (for deploying a new version without going through Apple review process! – this is huge!), Push notifications, Cloud packaging, Ionic Creator etc.
  • Ionic CLI (command line interface) uses Cordova in the backend and allows you to build (directly using Ionic CLI) apps for iOS and Android (just by doing ionic cordova build ios or ionic cordova build android).
  • Ionic uses Angular as a frontend framework so if you’re familiar with it, it will come as a bonus. Yes, the newest version of Ionic (currently 3) uses the newest and coolest Angular (currently 4) (which was a total rewrite from the Angular 1 version)
  • All in all, I personally think Ionic framework has a bright future, so if nothing else – give it a try I bet you’ll like the ease of making an app with it.

Do I have your attention now? Great, let’s install all the needed prerequisites in the next section and start using Ionic!

How is Ionic 3 different from Ionic 1 and 2

Josh Morony wrote about 7 Reasons Why Ionic 2 Is Better Than Ionic 1 and made a video about What Ionic 3 means to Ionic 2, and I encourage you to check them out to learn more about:

  • why Ionic 2 is totally different (and better) from Ionic 1 and
  • why Ionic 3 is not that much different from Ionic 2

The biggest change comes down to the fact that Ionic 2 and 3 use the new Angular (now at version 4), whereas Ionic 1 uses the old Angular 1.

Now, don’t get me wrong – we all seem to love the ‘new shiny things’, but I can tell you from my experience that even with Ionic 1 you can still make great apps! So, even if you’re awesome at Angular 1 I’d suggest you go for Ionic 3, as the benefits are truly amazing. Plus, you don’t want to be working in a 5 years ‘old’ technology, now do you? ?

Installing prerequisites for both Mac and Windows

We need to have Node.js and Git installed in order to install both Ionic and Cordova. If you already have (and if you’re a web developer chances are that you do) these tools installed, you can skip this section, and go straight to installing Ionic.

Installing Node.js

In order to download Node.js, visit https://nodejs.org/en/download/, where you’ll see the following options:

Installation on Windows and Mac OS is simple as you just have to download and run the appropriate installer and follow the familiar instructions (next, next, next, sure I accept, next, finish ).

If you have brew on your Mac then you can also install Node.js with:

brew install node

In both cases, npm (Node Package Manager – used to install other packages) will be installed along with Node.js.

To verify that you installed Node.js correctly on a Windows machine, run the following command in your Command prompt (or, even better, use Console 2):

node -v

You should get an output similar to: v8.0.0.

To verify that you installed Node.js correctly on your Mac, run the same command as above in your Terminal (or, even better, use iTerm), and you should get the same similar output as above.

To verify that you have npm install, just run: npm -v and you should get an output similar to: 5.0.1

Installing Git

In order to install Git, visit http://git-scm.com/download, where you’ll see the following options:

Installation on Windows and Mac OS is as simple as for Node.js as you just have to download and run the appropriate installer and follow the, yet again, familiar instructions.

To verify that you installed Git correctly on your Windows/Mac machine, run the following command in your Command prompt/Terminal:

git

You should get an output similar to:

usage: git [--version] [--help] [-C ] [-c name=value]
[--exec-path[=]] [--html-path] [--man-path] [--info-path]
[-p | --paginate | --no-pager] [--no-replace-objects] [--bare]
[--git-dir=] [--work-tree=] [--namespace=]
<command></command> []

These are common Git commands used in various situations:

start a working area (see also: git help tutorial)
clone Clone a repository into a new directory
init Create an empty Git repository or reinitialize an existing one

work on the current change (see also: git help everyday)
add Add file contents to the index
mv Move or rename a file, a directory, or a symlink
reset Reset current HEAD to the specified state
rm Remove files from the working tree and from the index

examine the history and state (see also: git help revisions)
bisect Use binary search to find the commit that introduced a bug
grep Print lines matching a pattern
log Show commit logs
show Show various types of objects
status Show the working tree status

grow, mark and tweak your common history
branch List, create, or delete branches
checkout Switch branches or restore working tree files
commit Record changes to the repository
diff Show changes between commits, commit and working tree, etc
merge Join two or more development histories together
rebase Reapply commits on top of another base tip
tag Create, list, delete or verify a tag object signed with GPG

collaborate (see also: git help workflows)
fetch Download objects and refs from another repository
pull Fetch from and integrate with another repository or a local branch
push Update remote refs along with associated objects

'git help -a' and 'git help -g' list available subcommands and some
concept guides. See 'git help <command></command>' or 'git help '
<command></command> to read about a specific subcommand or concept.
<command></command> ```

You don't have to worry if you don't know how to use Git since you won't be needing it directly (npm uses it to download packages). However, if you would like to learn (and there's no reason why you shouldn't expand your knowledge), you can check out this [good interactive tutorial](https://try.github.io/levels/1/challenges/1) made by CodeSchool.

## Installing Ionic
If you've installed the needed prerequisites from the previous section, then in order to install Ionic (both on Mac and Windows) you just have to run the following command:

`npm install ionic cordova -g`

Ionic uses [Cordova](https://cordova.apache.org/) in the background for packaging up the native app, thus the need for it. We're using the **-g** flag here, in order to install the packages **ionic** and **cordova** [globally](https://docs.npmjs.com/getting-started/installing-npm-packages-globally).

To verify that you've installed Ionic correctly on your Windows/Mac machine, run the following command in your Command prompt/Terminal:

`ionic -v`

You should get an output similar to:

`3.4.0`

To verify that you've installed Cordova correctly on your Windows/Mac machine, run the following command in your Command prompt/Terminal:

`cordova -v`

You should get an output similar to:

`7.0.1`

If you had Node.js installed before (and haven't used it much since), you may get a notification like this:


Upgrade warning – for the CLI to run correctly,
it is highly suggested to upgrade the following:

Please update your Node runtime to version >=0.12.x



To resolve this issue, just update Node.js; either by re-downloading it (on Windows) or by executing the following command in the Terminal (on a Mac): `brew update; brew upgrade node` > I would like to take a moment here and encourage you to post a comment about any problems you may come across (and from my experience from StackOverflow there tends to be quite a lot of them ?) with these (seemingly simple) installation tasks. There always tends to be some older version of Node.js installed, or problems with cache and npm, blah blah blah... I will do my best to try to resolve your issue. ## Using Ionic CLI If you run `ionic` in your Terminal/Command prompt you will get an output similar to the one below:

CLI 3.4.0
Usage:

$ ionic [–help] [–verbose] [–quiet] [] [options]
$ ionic [–confirm] [–no-interactive] [–yarn] [–no-timeout]

Global Commands:

docs ………………… Open the Ionic documentation website
info ………………… Print system/environment info
login ……………….. Login with your Ionic ID
signup ………………. Create an Ionic account
start ……………….. Create a new project
telemetry ……………. Opt in and out of telemetry

Project Commands:

You are not in a project directory.


What you got is actually a nice summary of the global commands that you can run using the ionic CLI, along with their short descriptions. _Btw, if you're wondering what this CLI thing is (and you haven't [Googled it yet](https://en.wikipedia.org/wiki/Command-line_interface)); it's actually an acronym for Command Line Interface, and in Ionic terms it's actually a tool that makes it easier to [start, build, run, and emulate, (and a lot more), Ionic apps](http://ionicframework.com/docs/cli/)._ In the following chapters we will cover most of these commands, but for now, let's not burden you too much, and let's do a quick skin deep dive by making a simple project using `ionic start` command. ## Starting a project with Ionic CLI by using the existing templates Cool, you've made it so far - I promise, you're going to see some code now! ![](http://i.imgur.com/Y8FXaWm.jpg) Ionic CLI allows you to start and initialize your project by using the aforementioned `ionic start` command. If you take a look at [the official documentation for the start command](http://ionicframework.com/docs/cli/start/) you will see something like the following definition: `ionic start [&lt;name&gt;] [&lt;template&gt;]` >❗If you're familiar with Ionic 1, then you'll notice that they've changed it a bit. If you still want to run Ionic 1 apps with an Ionic CLI version 3 or above, you need to pass in the `--type` flag like this: `ionic start myApp --type ionic1` If you just run `ionic start appname` the Ionic CLI will make a bootstrap application with all the needed parts in the **appname** folder, with the so-called **blank** template. In case you want to see the list of all the starter projects, you can run `ionic start --list`:

ionic start –list
tabs …………… ionic-angular A starting project with a simple tabbed interface
blank ………….. ionic-angular A blank starter project
sidemenu ……….. ionic-angular A starting project with a side menu with navigation in the content area
super ………….. ionic-angular A starting project complete with pre-built pages, providers and best practices for Ionic development.
conference ……… ionic-angular A project that demonstrates a realworld application
tutorial ……….. ionic-angular A tutorial based project that goes along with the Ionic documentation
aws ……………. ionic-angular AWS Mobile Hub Starter
tabs …………… ionic1 A starting project for Ionic using a simple tabbed interface
blank ………….. ionic1 A blank starter project for Ionic
sidemenu ……….. ionic1 A starting project for Ionic using a side menu with navigation in the content area
maps …………… ionic1 An Ionic starter project using Google Maps and a side menu


Additionally, you can use Github repo starters and Codepen URL starters. In our example, we will use the **sidemenu** template, so execute the following command from your Terminal/Command prompt: `ionic start Ionic3_1stTutorial sidemenu` You should see something similar to the following output:

✔ Creating directory ./Ionic3_1stTutorial – done!
[INFO] Fetching app base (https://github.com/ionic-team/ionic2-app-base/archive/master.tar.gz)
✔ Downloading – done!
[INFO] Fetching starter template sidemenu (https://github.com/ionic-team/ionic2-starter-sidemenu/archive/master.tar.gz)
✔ Downloading – done!
✔ Updating package.json with app details – done!
✔ Creating configuration file ionic.config.json – done!
[INFO] Installing dependencies may take several minutes!

npm install
✔ Running command – done!
npm install –save-dev –save-exact @ionic/cli-plugin-ionic-angular@latest
✔ Running command – done!
git init
✔ Running command – done!
git add -A
✔ Running command – done!
git commit -m “Initial commit” –no-gpg-sign
✔ Running command – done!

♬ ♫ ♬ ♫ Your Ionic app is ready to go! ♬ ♫ ♬ ♫

Run your app in the browser (great for initial development):
ionic serve

Run on a device or simulator:
ionic cordova run ios

Test and share your app on a device with the Ionic View app:
http://view.ionic.io

? Link this app to your Ionic Dashboard to use tools like Ionic View? No

Go to your newly created project: cd ./Ionic3_1stTutorial


## Running the Ionic application Now that we've initialized our Ionic application based on the **sidemenu** template, we have to run it in order to see what Ionic CLI generated for us. First, change the directory to the name of the application you gave in the `ionic start` command. In our case, that's: `cd Ionic3_1stTutorial`. If you open up the project in your editor (I use [Visual Studio Code](https://code.visualstudio.com/) with Solarized Dark theme nowadays, after being loyal, and paying ?, customer of [Sublime Text 3](http://www.sublimetext.com/3)) you will see the following folder structure: ![](http://i.imgur.com/cecGiB3.png) In the following chapters, we will spend most of the time in the **app** folder. > ❗ Those of you coming from Ionic 1 background be wary of the `www` folder - don't touch it at all, as this is where all the transpiled/compressed code is saved. `src/app` is your new `www` folder. > Since Ionic 3 is based on [Angular](https://angular.io/) framework, you will need at least a basic understanding of it, and you can start exploring it with a [free interactive tutorial](https://www.codeschool.com/courses/accelerating-through-angular) by CodeSchool, or you can check out my post for Pluralsight: [Getting started with Angular 2 by building a Giphy search application](https://www.pluralsight.com/guides/front-end-javascript/getting-started-with-angular-2-by-building-a-giphy-search-application). Please note that this is very different from Angular 1 that you (and me ?) was accustomed to. There are few ways in which you can get your Ionic application running: + `ionic serve` - starts the app in a local web browser + `ionic cordova emulate android` - starts the app in an emulator (in this example Android is used; you can also use **ios** if you're on a Mac and have all the prerequisites installed) + `ionic cordova run android` - starts the app on the actual device that's plugged into your computer + `ionic cordova build android` - creates an **.apk** file which you can physically copy to your Android device and run it (this scenario doesn't work for iOS devices in normal circumstances; you have to go through Xcode, as we'll describe in detail in the next chapter) So, now run the following command in your Terminal/Command prompt: `ionic serve` You should see the following similar output:

[INFO] Starting app-scripts server: –port 8100 –p 8100 –livereload-port 35729 –r 35729 –address 0.0.0.0 – Ctrl+C to
cancel
[13:56:20] watch started …
[13:56:20] build dev started …
[13:56:20] clean started …
[13:56:20] clean finished in 1 ms
[13:56:20] copy started …
[13:56:20] transpile started …
[13:56:22] transpile finished in 2.03 s
[13:56:22] preprocess started …
[13:56:22] deeplinks started …
[13:56:22] deeplinks finished in 11 ms
[13:56:22] preprocess finished in 13 ms
[13:56:22] webpack started …
[13:56:22] copy finished in 2.20 s
[13:56:29] webpack finished in 6.91 s
[13:56:29] sass started …
[13:56:30] sass finished in 953 ms
[13:56:30] postprocess started …
[13:56:30] postprocess finished in 10 ms
[13:56:30] lint started …
[13:56:30] build dev finished in 9.95 s
[13:56:30] watch ready in 10.03 s
[13:56:30] dev server running: http://localhost:8103/

[INFO] Development server running
Local: http://localhost:8103

[13:56:35] lint finished in 5.13 s
“`

Also, you should get your local browser started up automatically, pointing to the address http://localhost:8100/, with an output similar to the one on the image below (I resized the window for clarity – if you’re using Chrome, you can get the Window Resizer plugin, or use the Chrome Dev Tools Emulate feature):

Awesome thing about this is that you have automatically set up live reload feature, which means that as soon as you change the code in your app folder, the application will reload automatically so that you don’t have to keep pressing the F5 (&#8984;+R) key on your Windows (Mac) machine.

If you like, you can get this project on Github.

Conclusion

In this chapter we’ve gone through the options that you have in making an app these days. Then we explained what actually is Ionic framework and how to install it on both Mac and Windows. With the use of the Ionic CLI we started a project based on the sidemenu template, and finally, we ran it locally in the browser with the use of ionic serve command. In the next chapter, I’ll show you how to create your own calculator application by making use of Ionic Creator.

How to get started with @Ionicframework 3 on #Mac and #Windows https://t.co/DZrp4q5ott pic.twitter.com/SbGfTbXzh0

— Nikola Brežnjak (@HitmanHR) July 16, 2017

Ionic3

How to create the simplest TODO application with Ionic 3

TL;DR

This is the simplest example which shows how to create a simple TODO application with Ionic 3 in just a few lines of code.

Quickstart

To see it in action:

  • Clone the finished project from Github
  • Make sure you’ve got the newest Ionic CLI (see this post for more instructions)
  • Run ionic serve
  • The app in action (after adding few items and swiping to delete one):

Step by step on how to create this yourself from scratch

Create a new blank Ionic project with ionic start Ionic3ServerSendTest blank

Template

Copy the following code to src/pages/home/home.html file:

Here we have three parts:

  • an input (ion-input) field where we enter the text for our TODO. We’ve put a ngModel of name todo on it – we will be able to reference this in the code by this same variable name.
  • a button (ion-button) which when clicked calls the function called add, which we’ll define in our src/pages/home/home.ts file shown below.
  • a list (ion-list) with multiple items (ion-item) in it. Also, we’ve made use of the ion-item-sliding (learn more about it from the docs here). We are repeating the ion-item-sliding component as many times as we have items in the todos array (you’ll see where we set that in the home.ts file, as mentioned above).

Code

To the src/pages/home/home.ts file copy the following content:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {
    todos: string[] = [];
    todo: string;

    constructor(public navCtrl: NavController) {

    }

    add() {
        this.todos.push(this.todo);
        this.todo = "";
    }

    delete(item) {
        var index = this.todos.indexOf(item, 0);
        if (index > -1) {
            this.todos.splice(index, 1);
        }
    }
}

The only thing that differs here from the basic blank template generated code is the todos and todo variables which we use for holding the array of todos and a current todo that’s connected to the model in the input box.

The add function pushes the current todo that we have in the input box at the time of pressing the Add button into the todos array.

The delete function first finds the index of the item that we want to delete from the list and then, by using the splice function, it deletes the item from the todos array.

Running the app

Just run ionic serve or even better yet ionic lab from the root directory of your Ionic app and you’ll have the app running locally in your browser tab with live reload option turned on.

Conclusion

That’s it. It doesn’t get any easier than this. Sure, this is as simple as it gets; there’s no persistence or anything, that’s for you to play with. Or, well, I may add that in the next tutorial…

‘Till then, have a great one, and a happy 4th of July to all my friends across the big pond 😉

How to create the simplest #TODO application with #Ionic 3 https://t.co/xvjmXVruBH

— Nikola Brežnjak (@HitmanHR) July 4, 2017

Ionic3

Posting data from Ionic 3 app to a PHP server

TL;DR

This is the simplest example which shows how to POST data from an Ionic 3 app to a PHP server.

The tutorial covering the Ionic version 1 can be found here, and the tutorial covering the Ionic version 2 can be found here.

Quickstart

To see it in action:

    1. Clone the finished project from Github
    2. Make sure you’ve got the newest Ionic CLI (see below for instructions)
    3. Run ionic serve
    4. You should see something like this:
      ionic2ServerPost

If you want to make it work from your server:

  1. Make sure you’ve got the newest Ionic CLI (see below for instructions)
  2. Clone the finished project from Github
  3. Upload the PHP/api.php file to your server
  4. In the src/pages/home/home.ts file adjust the link variable (line #21) to point to your server
  5. Run ionic serve

Getting started with Ionic 3

After neglecting Ionic 3 (and for the most part Ionic 2) for far too long due to the overburdening work I still have on my Ionic 1 apps, I finally got some time to take a look at Ionic 3 and update the most popular post about Ionic on my blog, so here you go and enjoy.

In general, from me playing just a bit with Ionic 3, I have to say I love it, so expect some more posts about it soon-ish…

To install the Ionic SDK and create Ionic 3 projects, you need to install the latest Ionic CLI:

npm install -g ionic

You don’t need to worry about this messing up your current ionic CLI since the new one still works with old Ionic 1 projects.

Just for reference, here’s what my ionic info says now:

$> ionic info 

global packages:

    @ionic/cli-utils : 1.4.0
    Ionic CLI        : 3.4.0

local packages:

    @ionic/app-scripts              : 1.3.7
    @ionic/cli-plugin-ionic-angular : 1.3.1
    Ionic Framework                 : ionic-angular 3.4.2

System:

    Node       : v8.0.0
    OS         : macOS Sierra
    Xcode      : Xcode 8.3.3 Build version 8E3004b 
    ios-deploy : 1.9.1 
    ios-sim    : 5.0.13 
    npm        : 5.0.1 

Step by step on how to create this yourself from scratch

  1. Create a new blank Ionic project with:
    ionic start Ionic3ServerSendTest blank
  2. Copy the following code to src/pages/home/home.html file:
    <ion-header>
     <ion-navbar>
     <ion-title>
     Ionic3 Server Send Test
     </ion-title>
     </ion-navbar>
    </ion-header>
    
    <ion-content padding>
     <ion-list>
     <ion-item>
     <ion-label floating>Username</ion-label>
     <ion-input type="text" name="username" [(ngModel)]="data.username"></ion-input>
     </ion-item>
    
     <button ion-button block (click)="submit()">Submit to server</button>
     </ion-list>
    
     <ion-card>
     <ion-card-header>
     Response
     </ion-card-header>
    
     <ion-card-content>
     <b>{{data.response}}</b>
     </ion-card-content>
     </ion-card>
    </ion-content>
    

    Here you basically created a form with an username input field and with a button which acts as a submit button.

    Once the button is clicked AngularJS should handle it within the submit() function which we will define in our src/pages/home/home.ts file (shown below).

    Input username uses  the new syntax for ng-model , and it binds to the variable data.username, so that you can then use it in your submit() function (shown below).

    Components are a bit different in Ionic 3 now, so I encourage you can take a look at the official documentation.

  3. On your server, create an api.php file with the following content:
    <?php
        //http://stackoverflow.com/questions/18382740/cors-not-working-php
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');    // cache for 1 day
        }
    
        // Access-Control headers are received during OPTIONS requests
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
                header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
            exit(0);
        }
    
    
        //http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined
        $postdata = file_get_contents("php://input");
        if (isset($postdata)) {
            $request = json_decode($postdata);
            $username = $request->username;
    
            if ($username != "") {
                echo "Server returns: " . $username;
            }
            else {
                echo "Empty username parameter!";
            }
        }
        else {
            echo "Not called properly with username parameter!";
        }
    ?>

    As you can see from the code, the first part is explained in detail in this StackOverflow question, and it basically solves the CORS issue that you would otherwise run into.

    The second part, explained in detail in this StackOverflow question,  deals with the way you POST data from Ionic to your PHP server. The gist is that since we POSTed in a JSON format, we have to json_decode  the data that comes to your PHP server.

  4. To the file src/pages/home/home.ts file copy the following content and adjust the link variable to point to the file on your server:
    import { Component } from '@angular/core';
    import { NavController } from 'ionic-angular';
    import { Http } from '@angular/http'; //https://stackoverflow.com/questions/43609853/angular-4-and-ionic-3-no-provider-for-http
    
    @Component({
     selector: 'page-home',
     templateUrl: 'home.html'
    })
    
    export class HomePage {
     data:any = {};
    
     constructor(public navCtrl: NavController, public http: Http) {
     this.data.username = '';
     this.data.response = '';
    
     this.http = http;
     }
    
     submit() {
     var link = 'http://nikola-breznjak.com/_testings/ionicPHP/api.php';
     var myData = JSON.stringify({username: this.data.username});
     
     this.http.post(link, myData)
     .subscribe(data => {
     this.data.response = data["_body"]; //https://stackoverflow.com/questions/39574305/property-body-does-not-exist-on-type-response
     }, error => {
     console.log("Oooops!");
     });
     }
    }

    As with the Ionic 2 tutorial, things have changed a lot since Ionic 1, but in Ionic 3 (if you come from Ionic 2) you shouldn’t have any problems. Anyways, practice makes perfect, so make sure you put in the hours of deliberate practice.

    In this file, we import the Http component from Angular. You can check out the link in the comment to learn that you also need to import and inject HttpModule in src/app/app.module.ts (two new lines that I’ve added are bolded):

    import { BrowserModule } from '@angular/platform-browser';
    import { ErrorHandler, NgModule } from '@angular/core';
    import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
    import { SplashScreen } from '@ionic-native/splash-screen';
    import { StatusBar } from '@ionic-native/status-bar';
    import { HttpModule} from '@angular/http';
    
    import { MyApp } from './app.component';
    import { HomePage } from '../pages/home/home';
    
    @NgModule({
     declarations: [
     MyApp,
     HomePage
     ],
     imports: [
     BrowserModule,
     IonicModule.forRoot(MyApp),
     HttpModule
     ],
     bootstrap: [IonicApp],
     entryComponents: [
     MyApp,
     HomePage
     ],
     providers: [
     StatusBar,
     SplashScreen,
     {provide: ErrorHandler, useClass: IonicErrorHandler}
     ]
    })
    export class AppModule {}

    Inside the HomePage class, we now have a constructor where we’re setting some default values. Important to note, see how we’re passing in Http via the constructor parameter.

    Inside the submit function we use the http service to post to our API endpoint with some data. Make note of how we use the subscribe function to handle data once it arrives. Also, make sure you check out the StackOverflow link in the comment as a solution of how to access plain text response.

  5. Run ionic serve  from the root directory of your Ionic app

That’s all folks, I hope this tutorial helps you in starting your journey towards Ionic3 & Angular4!

Posting data from #Ionic 3 app to a #PHP server https://t.co/QYKiQtq1kJ

— Nikola Brežnjak (@HitmanHR) June 21, 2017

Ionic

4th Ionic framework meetup in Čakovec

Our 4th Ionic Framework Meetup was held last Thursday, 13th of October. It was titled Designing with Macaw, and it was all about design this time.

I would like to thank Goran Levačić, the leader of incubation and education in TICM who was the presenter this time and who did a great job presenting the material and showing us some practical things in InVision and Macaw.

It will be interesting to see what the future brings since Macaw was acquired by InVision just recently and they announced that they would combine these two tools into one product till the end of 2016. This way both designers and developers will have a common platform through which they will be able to work more efficiently together.

Few pics from the meetup:

In case you’re interested in next events, be sure to check out the meetup page and join the discussion there.

Ionic

Cordova plugin for VoIP push notifications

TL;DR

This plugin didn’t exist, so I made it – Cordova plugin for receiving VoIP push notifications on iOS 8.0+ only.

Installation

For Ionic:

ionic plugin add cordova-ios-voip-push

For Cordova:

cordova plugin add cordova-ios-voip-push

Usage

var push = VoIPPushNotification.init();

push.on('registration', function(data) {
    log("[Ionic] registration callback called");
    log(data);

    //data.deviceToken;
    //do something with the device token (probably save it to your backend service)
});

push.on('notification', function(data) {
    log("[Ionic] notification callback called");
    log(data);

    // do something based on received data
});

push.on('error', function(e) {
    log(e);
});

Please see the Ionic demo for the exact usage example.

Running the demo

Ionic setup

Clone this repo:

git clone https://github.com/Hitman666/cordova-ios-voip-push.git

CD into the cloned project and the Ionic demo project:

cd cordova-ios-voip-push && cd ionicDemo

Install the dependencies:

npm install && bower install

Install the platform and plugins (please note that this process may take a while to complete):

ionic state reset

Add the plugin (either one of three options would work):

ionic plugin add cordova-ios-voip-push

or

ionic plugin add ../thePlugin/VoIPPushNotification

or like this:

ionic plugin add https://github.com/Hitman666/cordova-ios-voip-push.git

Prepare the project:

ionic prepare ios

Open the project in XCode by going into platforms/ios and opening up the pluginTest.xcodeproj file.

XCode setup

If you don’t have an AppID and VoIP push certificate created in your Apple developer account, you can do so by following my instructions from the How to create a native iOS app that can receive VoIP push notifications tutorial.

Take your time to do that an then come back, I’ll wait.

To use the VoIP push in the app, you need to turn ON the Background Modes for your app and check few of the checkboxes:

Make sure you select the following options:

  • Audio, Airplay, and Picture in Picture
  • Voice over IP
  • Background fetch
  • Remote notifications

Next, you need to add PushKit framework to your project:

Also (yeah, I know, a lot of setup), you need to make sure that you set the appropriate Bundle Identifier. You should have read about this in the tutorial I linked above.

After you run the project, in the XCode console you should see

and on your device:

You can send VoIP pushes to yourself by editing the simplepush.php file (in the pushSendingScript folder from the Github repo). Just make sure you add your own device id that you’ll see show up on your phone. You have more options to send VoIP push, two of which you can read in the post linked few times above.

!TL;DR

Disclaimer:
This tutorial was inspired by the official phonegap-plugin-push plugin, and the fact that this kind of VoIP support didn’t exist. There were requests for it here, here and here. As well as on freelance sites like here, here – hehe, hope these guys will send some donations to my favorite charity if they end up using this now 😉

Also, I don’t ‘do’ ObjectiveC for a living (but I may change my mind after completing this :)), so I would really appreciate the constructive feedback in making this plugin better, so I look forward to your comments and potential pull requests!

In my previous tutorial I showed how to create a native iOS app with Swift (ObjectiveC code also available) that can receive VoIP push notifications sent with Houston, custom PHP script or through Amazon SNS.

In this tutorial I’m going to present to you the Cordova plugin that does the same thing; it allows hybrid iOS applications to receive the VoIP push notifications.

Building Cordova plugins

I won’t go into the details of Cordova plugin building in this document. If you’re new to building Cordova plugins, you can check out this tutorial and official docs, as they were indispensable in my quest to learn as much as possible about it.

plugin.xml

<?xml version='1.0' encoding='utf-8'?>
<plugin id="com.nikola-breznjak.voippush" version="1.0.0" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
    <name>VoIPPushNotification</name>
    <js-module name="VoIPPushNotification" src="www/VoIPPushNotification.js">
        <clobbers target="VoIPPushNotification" />
    </js-module>

    <platform name="ios">
        <config-file target="config.xml" parent="/*">
            <feature name="VoIPPushNotification">
                <param name="ios-package" value="VoIPPushNotification" />
            </feature>
        </config-file>

        <header-file src="src/ios/VoIPPushNotification.h" />
        <source-file src="src/ios/VoIPPushNotification.m" />
    </platform>
</plugin>

In this file you basically define:

  • for which platform is this plugin (<platform name="ios">)
  • where the source files of your plugin will be (header-file and source-file elements)
  • where is the JavaScript file that will be the bridge from Cordova to native code (js-module tag src property)
  • what will be the plugins name by which you’ll reference it in the Cordova/Ionic code (<clobbers target="VoIPPushNotification" />)

www/VoIPPushNotification.js

This file, stripped of it’s comments is very short (75 LOC):

var exec = cordova.require('cordova/exec');

var VoIPPushNotification = function() {
    this._handlers = {
        'registration': [],
        'notification': [],
        'error': []
    };

    // triggered on registration and notification
    var that = this;
    var success = function(result) {
        if (result && result.registration === 'true') {
            that.emit('registration', result);
        }
        else if (result) {
            that.emit('notification', result);
        }
    };

    // triggered on error
    var fail = function(msg) {
        var e = (typeof msg === 'string') ? new Error(msg) : msg;
        that.emit('error', e);
    };

    // wait at least one process tick to allow event subscriptions
    setTimeout(function() {
        exec(success, fail, 'VoIPPushNotification', 'init');
    }, 10);
};

VoIPPushNotification.prototype.on = function(eventName, callback) {
    if (this._handlers.hasOwnProperty(eventName)) {
        this._handlers[eventName].push(callback);
    }
};

VoIPPushNotification.prototype.off = function (eventName, handle) {
    if (this._handlers.hasOwnProperty(eventName)) {
        var handleIndex = this._handlers[eventName].indexOf(handle);
        if (handleIndex >= 0) {
            this._handlers[eventName].splice(handleIndex, 1);
        }
    }
};

VoIPPushNotification.prototype.emit = function() {
    var args = Array.prototype.slice.call(arguments);
    var eventName = args.shift();

    if (!this._handlers.hasOwnProperty(eventName)) {
        return false;
    }

    for (var i = 0, length = this._handlers[eventName].length; i < length; i++) {
        var callback = this._handlers[eventName][i];
        if (typeof callback === 'function') {
            callback.apply(undefined,args);
        } else {
            console.log('event handler: ' + eventName + ' must be a function');
        }
    }

    return true;
};


module.exports = {
    init: function(options) {
        return new VoIPPushNotification(options);
    },

    VoIPPushNotification: VoIPPushNotification
};

This code follows the structure of the phonegap-plugin-push push.js.

Once you call the init method, you get the new VoIPPushNotification object which then exposes the methods for listening to the registration, notification and error events.

src/ios/VoIPPushNotification.h

#import <Cordova/CDV.h>
#import <PushKit/PushKit.h>

@interface VoIPPushNotification : CDVPlugin <PKPushRegistryDelegate>

@property (nonatomic, copy) NSString *VoIPPushCallbackId;
- (void)init:(CDVInvokedUrlCommand*)command;

@end

Since we’re writing in ObjectiveC, we need to define the functions in the .h file. Here we do few things:

  • import Cordova and PushKit
  • add an instance property VoIPPushCallbackId
  • add an init function declaration

src/ios/VoIPPushNotification.m

#import "VoIPPushNotification.h"
#import <Cordova/CDV.h>

@implementation VoIPPushNotification

@synthesize VoIPPushCallbackId;

- (void)init:(CDVInvokedUrlCommand*)command
{
  self.VoIPPushCallbackId = command.callbackId;
  NSLog(@"[objC] callbackId: %@", self.VoIPPushCallbackId);

  //http://stackoverflow.com/questions/27245808/implement-pushkit-and-test-in-development-behavior/28562124#28562124
  PKPushRegistry *pushRegistry = [[PKPushRegistry alloc] initWithQueue:dispatch_get_main_queue()];
  pushRegistry.delegate = self;
  pushRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
}

- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type{
    if([credentials.token length] == 0) {
        NSLog(@"[objC] No device token!");
        return;
    }

    //http://stackoverflow.com/a/9372848/534755
    NSLog(@"[objC] Device token: %@", credentials.token);
    const unsigned *tokenBytes = [credentials.token bytes];
    NSString *sToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                         ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                         ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                         ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];

    NSMutableDictionary* results = [NSMutableDictionary dictionaryWithCapacity:2];
    [results setObject:sToken forKey:@"deviceToken"];
    [results setObject:@"true" forKey:@"registration"];

    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:results];
    [pluginResult setKeepCallback:[NSNumber numberWithBool:YES]]; //[pluginResult setKeepCallbackAsBool:YES];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:self.VoIPPushCallbackId];
}

- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type
{
    NSDictionary *payloadDict = payload.dictionaryPayload[@"aps"];
    NSLog(@"[objC] didReceiveIncomingPushWithPayload: %@", payloadDict);

    NSString *message = payloadDict[@"alert"];
    NSLog(@"[objC] received VoIP msg: %@", message);

    NSMutableDictionary* results = [NSMutableDictionary dictionaryWithCapacity:2];
    [results setObject:message forKey:@"function"];
    [results setObject:@"someOtherDataForField" forKey:@"someOtherField"];

    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:results];
    [pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:self.VoIPPushCallbackId];
}

@end

In the implementation file we define our functions. The first one is init, and here we basically register for VoIP push notifications by using PKPushRegistry.

Then, to satisfy that, we implement two functions: didUpdatePushCredentials and didReceiveIncomingPushWithPayload.

The first one is triggered with the device token, which we then send back to the ‘JS world’. We listen for this in our Ionic/Cordova apps and send this information to our backend so that later when we’re going to send the push we know to which device id.

The second one is triggered when we receive the actual VoIP push notification. In this example, we take out the message (@alert) and return it to the ‘JS world’. In my particular case, this can be a message with a certain keyword, so that then I know what to do in my app based on that keyword.

Again, I have to stress here that you may wanna alter this to your liking and process even more data which you receive through the VoIP push notification.

Conclusion

I hope this plugin will come handy to you. Also, I hope that this will give you enough information so that you’ll be dangerous enough to go and fiddle with the code yourself.

As I’ve mentioned before, I would really appreciate the constructive feedback so that we can make this plugin better, so I look forward to your comments and optional pull requests.

Btw, I updated these posts with this solution:

  • StackOverflow post
  • Ionic framework forum
  • phonegap-plugin-push plugin

and I have also asked the main maintainer of phonegap-plugin-push plugin if this would make sense to put as a PR on that plugin.

I will update you on the progress of all this, and till then – code on!

#Cordova plugin for #VoIP push notifications https://t.co/jkn56YWGTU

— Nikola Brežnjak (@HitmanHR) September 30, 2016

Angular 2

How to use http in Angular 2 via angular-cli?

I initially tested and wrote a tutorial for Pluralsight by using the angular-cli version 1.0.0-beta.9.

However, I’ve tried today with the latest version and for the life of me I couldn’t figure out how to use HTTP to call some service.

In the end, I figured what the issue was, so I’m putting it out here so it may be useful to someone else as well.

So, when I installed angular-cli with npm install -g angular-cli I haven’t at first noticed this error:
UNMET PEER DEPENDENCY [email protected]

What I ended up doing now was

npm install webpack -g && npm install webpack --save-dev

and now I can normally include Http into my component like this:

import { Http, Response } from '@angular/http';

and then use it within a class like this:

Hope this helps someone.

Ionic

3rd Ionic framework meetup in Čakovec

Yesterday I held the third Ionic framework meetup in Čakovec titled Getting started with Angular 2.

I showed how to get started with Angular 2 by using the angular-cli project to start, scaffold and test Angular 2 applications. You can read the tutorial that this talk was based on here: Getting started with Angular 2 by building a Giphy search application.

Two pics from the meetup:

thumb_img_7241_1024

thumb_img_7243_1024

I would like to thank Goran Levačić, the leader of incubation and education in TICM, for securing us the place for this meetup and company Axiom for the provided drinks.

In case you’re interested in next events, be sure to check out the meetup page and join the discussion there.

CodeProject, NodeJS

Raneto Google OAuth login

TL;DR

Raneto allows only basic username/password authentication, so I added Google OAuth support. This option can be turned on by setting the googleoauth option in the config.default.js file to true, and by supplying the OAuth config object as outlined in the guides below. Additionally, you can allow only emails from the certain domain to use the service with one config setting.

The basic idea was taken from the Google Cloud Platform Node.js guide.

This has been submitted as a pull request on the official Raneto Github repository. This is my way of saying thanks to an awesome author of Raneto. edit: 13.09.2016: The pull request was approved and merged!.

Steps on how to reproduce this on fresh copy

Below are the steps one needs to take to get this working on a fresh copy of Raneto. In case this won’t make it to the official repo, you can clone my fork here. Just make sure you set your Google OAuth credentials properly (more about this in the X section).

Install packages via npm

Make sure you first install Raneto dependencies after you clone it.

Install the following packages:

  • npm install passport --save-dev
  • npm install passport-google-oauth20 --save-dev

Editing the app/index.js file

  • Add passport: var passport=require('passport'); just after raneto is required.
  • Add oauth2 middleware: var oauth2= require('./middleware/oauth2.js'); in the config block, just afer error_handler.js middleware.
  • Change secret to secret:config.secret, in the // HTTP Authentication section.
  • >>> Remove the rn-login route app.post('/rn-login', route_login);
  • >>> Remove the logout route: app.get('/logout', route_logout);
  • Add the following Oauth settings, just before the app.post('/rn-login', route_login); line:
// OAuth2
if (config.googleoauth === true) {
app.use(passport.initialize());
app.use(passport.session());
app.use(oauth2.router(config));
app.use(oauth2.template);
}
  • Change the Online Editor Routes to look like this now:
// Online Editor Routes
if (config.allow_editing === true) {
if (config.googleoauth === true) {
app.post('/rn-edit', oauth2.required, route_page_edit);
app.post('/rn-delete', oauth2.required, route_page_delete);
app.post('/rn-add-page', oauth2.required, route_page_create);
app.post('/rn-add-category', oauth2.required, route_category_create);
}
else {
app.post('/rn-edit', authenticate, route_page_edit);
app.post('/rn-delete', authenticate, route_page_delete);
app.post('/rn-add-page', authenticate, route_page_create);
app.post('/rn-add-category', authenticate, route_category_create);
}
}
  • Set the root routes to be like this:
// Router for / and /index with or without search parameter
if (config.googleoauth === true) {
app.get('/:var(index)?', oauth2.required, route_search, route_home);
app.get(/^([^.]*)/, oauth2.required, route_wildcard);
}
else {
app.get('/:var(index)?', route_search, route_home);
app.get(/^([^.]*)/, route_wildcard);
}

Editing the app/middleware/authenticate.js file

Change the res.redirect(403, '/login'); line to be:

if (config.googleoauth === true) {
res.redirect('/login');
}
else {
res.redirect(403, '/login');
}

Editing the app/routes/login_page.route.js file

Add the googleoauth variable to the return object like this:

return res.render('login', {
layout : null,
lang : config.lang,
rtl_layout : config.rtl_layout,
googleoauth : config.googleoauth
});

Add the oauth2.js file

Create a new file oauth2.js in the app/middleware folder with the following content:

// Copyright 2015-2016, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

var express = require('express');
var debug = require('debug')('raneto');

// [START setup]
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth20').Strategy;

function extractProfile (profile) {
var imageUrl = '';
if (profile.photos &amp;&amp; profile.photos.length) {
imageUrl = profile.photos[0].value;
}
return {
id: profile.id,
displayName: profile.displayName,
image: imageUrl
};
}

// [START middleware]
// Middleware that requires the user to be logged in. If the user is not logged
// in, it will redirect the user to authorize the application and then return
// them to the original URL they requested.
function authRequired (req, res, next) {
if (!req.user) {
req.session.oauth2return = req.originalUrl;
return res.redirect('/login');
}
next();
}

// Middleware that exposes the user's profile as well as login/logout URLs to
// any templates. These are available as `profile`, `login`, and `logout`.
function addTemplateVariables (req, res, next) {
res.locals.profile = req.user;
res.locals.login = '/auth/login?return=' +
encodeURIComponent(req.originalUrl);
res.locals.logout = '/auth/logout?return=' +
encodeURIComponent(req.originalUrl);
next();
}
// [END middleware]

function router(config) {
// Configure the Google strategy for use by Passport.js.
//
// OAuth 2-based strategies require a `verify` function which receives the
// credential (`accessToken`) for accessing the Google API on the user's behalf,
// along with the user's profile. The function must invoke `cb` with a user
// object, which will be set at `req.user` in route handlers after
// authentication.
passport.use(new GoogleStrategy({
clientID: config.oauth2.client_id,
clientSecret: config.oauth2.client_secret,
callbackURL: config.oauth2.callback,
hostedDomain: config.hostedDomain || '',
accessType: 'offline',

}, function (accessToken, refreshToken, profile, cb) {
// Extract the minimal profile information we need from the profile object
// provided by Google
cb(null, extractProfile(profile));
}));

passport.serializeUser(function (user, cb) {
cb(null, user);
});
passport.deserializeUser(function (obj, cb) {
cb(null, obj);
});
// [END setup]

var router = express.Router();

// Begins the authorization flow. The user will be redirected to Google where
// they can authorize the application to have access to their basic profile
// information. Upon approval the user is redirected to `/auth/google/callback`.
// If the `return` query parameter is specified when sending a user to this URL
// then they will be redirected to that URL when the flow is finished.
// [START authorize]
router.get(
// Login url
'/auth/login',

// Save the url of the user's current page so the app can redirect back to
// it after authorization
function (req, res, next) {
if (req.query.return) {
req.session.oauth2return = req.query.return;
}
next();
},

// Start OAuth 2 flow using Passport.js
passport.authenticate('google', { scope: ['email', 'profile'] })
);
// [END authorize]

// [START callback]
router.get(
// OAuth 2 callback url. Use this url to configure your OAuth client in the
// Google Developers console
'/auth/google/callback',

// Finish OAuth 2 flow using Passport.js
passport.authenticate('google'),

// Redirect back to the original page, if any
function (req, res) {
req.session.loggedIn = true;
var redirect = req.session.oauth2return || '/';
delete req.session.oauth2return;
res.redirect(redirect);
}
);
// [END callback]

// Deletes the user's credentials and profile from the session.
// This does not revoke any active tokens.
router.get('/auth/logout', function (req, res) {
req.session.loggedIn = false;
req.logout();
res.redirect('/login');
});
return router;
}

module.exports = {
extractProfile: extractProfile,
router: router,
required: authRequired,
template: addTemplateVariables
};

This is a changed file based on the Google Node.js official example file. Notable differences are in Google strategy settings which basically load settings from our settings config:

clientID: config.oauth2.client_id,
clientSecret: config.oauth2.client_secret,
callbackURL: config.oauth2.callback,
hostedDomain: config.hostedDomain || '',

We’ll define these settings the config.default.js file now.

Editing the example/config.default.js file

Change/add the following settings:

allow_editing : true,
authentication : true,
googleoauth: true,
oauth2 : {
client_id: 'GOOGLE_CLIENT_ID',
client_secret: 'GOOGLE_CLIENT_SECRET',
callback: 'http://localhost:3000/auth/google/callback',
hostedDomain: 'google.com'
},
secret: 'someCoolSecretRightHere',

Google OAuth2 Credentials

Oauth2 settings (GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET) can be found in your Google Cloud Console-&gt;API Manager-&gt;Credentials project settings (create a project if you don’t have one yet):

The callback, if testing locally, can be set as shown above (http://localhost:3000/auth/google/callback). The hostedDomain option allows certain domains – for your use case you may want to set this to your domain.

Google+ API

If you get an error like:

Access Not Configured. Google+ API has not been used in project 701766813496 before, or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/plus/overview?project=701766813496 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.

Make sure you enable Google+ API for your project:

Adding Zocial CSS

To add support for the nice Zocial social buttons, download this file from their Github repo to the themes/default/public/styles/ folder.

Editing the themes/default/templates/layout.html file

Replace the login form with:

We added two scenarios for when we have Google OAuth enabled (config.googleoauth) and when we don’t (defaulting to the current Raneto behavior).

Editing the themes/default/templates/login.html file

Add zocial reference:

“

Replace the whole form-bottom classed div with the following code:

Same thing here as well. If we have Google OAuth enabled (config.googleoauth) then we show the new Google login button and hide the rest. Otherwise, we default it to the current Raneto behavior.

Testing

Congratulations, you’re done! Now, to test this locally just run the npm start from the root of your project and go to http://localhost:3000 and you should see this:

After logging in, you should see something like this:

Hope this helps someone!

#Raneto Google OAuth login step by step https://t.co/rWnoXFl0LO

— Nikola Brežnjak (@HitmanHR) September 7, 2016

Page 3 of 13« First...«2345»10...Last »

Recent posts

  • Discipline is also a talent
  • Play for the fun of it
  • The importance of failing
  • A fresh start
  • Perseverance

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (35)
  • Daily Thoughts (77)
  • Go (3)
  • iOS (5)
  • JavaScript (127)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (2)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (77)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (40)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak