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
Ionic, Stack Overflow

Ionic View Manage Apps

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

I uploaded a test app to Ionic (don’t know the exact name for this) with the command ionic upload from the command line, and I can access them nicely with the Ionic View application I have installed on my iPhone.

However, I remember that they have a web interface for this too, but can’t find the link for the life of me. I searched the website, went through my emails, googled, but nothing. I even found the same question on the official forum – sadly unanswered.

I actually found the answer to this myself:

And, sure enough, after going through my deleted emails I found a welcome email from Ionic stating that the login is at https://apps.ionic.io/login. Will reply to that official post too…

CodeProject, Ionic

Adding AdMob to Ionic framework application step by step

In case you’re looking for a way to implement Google AdMob ads in Ionic framework 3, then check out this tutorial: How to make money with Google AdMob ads in Ionic framework 3.

If you want, you can take a look at the screencast of this tutorial. This is actually my first shocked screencast blog post so go easy on me 🙂

I’ve been searching for a start to end tutorial on this but with no luck. Now, when I finally figured out how to use it, I’m documenting the exact steps which I did in order to get the AdMob working inside my Ionic app. You can fork the project from GitHub or download and test the .apk file on your device.

I broke down the steps in two parts: AdMob settings and Ionic settings.

AdMob settings

Let’s start with AdMob settings:

  1. Sign in /Sign up for AdMob at https://www.google.com/admob/
  2. Click the Monetize new app button:
    Screen Shot 2015-05-05 at 23.21.06
  3. If your app is not yet published you can add it manually:
    Screen Shot 2015-05-05 at 23.23.07
  4. Create new tracking ID:
    Screen Shot 2015-05-05 at 23.25.20
  5. Configure the adds type, size, placement, style, name:
    Screen Shot 2015-05-05 at 23.26.29
  6. You can read additional info on how to implement GA and AdMob, but for now let’s just click Done:
    Screen Shot 2015-05-05 at 23.28.10
  7. You will now see the following similar screen:
    Screen Shot 2015-05-05 at 23.30.11
    The most important thing to note here is this Ad unit ID, which in my test case is
    ca-app-pub-7957971173858308/3599533362

Ionic settings

I’m counting on the fact that you know how to use Ionic since you’re looking for a specific topic like this, so am going skip the part of actually explaining how to use the Ionic cli. Ok, enough chit-chat, now I’m going to show you the steps on how to implement AdMob in your Ionic project:

  1. Start a new Ionic blank project:
    ionic create IonicAdMobTest blank
  2. Add the platform for which you want to build the application:
  3. ionic platform add android

    In case you’re developing on a Mac, you can also choose to add:

    ionic platform add ios
  4. Add the cordova-plugin-admob plugin by entering the following command in your command prompt when in the root folder of your project:
    cordova plugin add com.rjfun.cordova.plugin.admob

    As a side note, you can always check the list of all installed plugins by executing:

    cordova plugin list
  5. Add the following code to your app.js file (located in the www folder) inside the .run function:
    .run(function($ionicPlatform) {
        $ionicPlatform.ready(function() {
            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            if (window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            }
            if (window.StatusBar) {
                // org.apache.cordova.statusbar required
                StatusBar.styleDefault();
            }
    
            if(window.plugins && window.plugins.AdMob) {
                var admob_key = device.platform == "Android" ? "ca-app-pub-7957971173858308/3666912163" : "ca-app-pub-7957971173858308/3666912163";
                var admob = window.plugins.AdMob;
                admob.createBannerView( 
                    {
                        'publisherId': admob_key,
                        'adSize': admob.AD_SIZE.BANNER,
                        'bannerAtTop': false
                    }, 
                    function() {
                        admob.requestAd(
                            { 'isTesting': false }, 
                            function() {
                                admob.showAd(true);
                            }, 
                            function() { console.log('failed to request ad'); }
                        );
                    }, 
                    function() { console.log('failed to create banner view'); }
                );
            }
        });
    })

    Of course, change it according to your own admob_key which you obtained in the first part (step 8).

  6. Start the emulator by running:
    ionic build ios && ionic emulate ios
    
    //or, for android
    ionic build android && ionic emulate android
  7. and you should get the following screen in your emulated application:
    IonicAdMobTest
  8. You can clone the project from GitHub, or download the .apk (unzip needed) file and test on your Android device.

That’s all folks, hope this helps someone by saving time on endless testing as I did :/

Breaking News, Ionic

Ionic Analytics Alpha

From an official blog post, Ionic Analytics Alpha

gives you all the data you need to better understand and optimize your push notifications, deployments, and much, much more.

The go on to say that

You can chart your app’s progress, from the time of its initial release, and see which marketing strategies were most (or least) effective. You can even gain insights into your app’s demographics, allowing you to see how well your app is doing within a given population.

Some of the data this will be able to provide is:

  • How many people log into my app every day?
  • How many of those continue to use my app after a week? A month? A year?
  • With which parts of my app are users interacting the most?
  • What are users doing right now in my app?

If you were like me – thinking that this will cost some amount, here’s what they say:

During the alpha period, Ionic Analytics will be 100% free. In the future, we’ll release tiered pricing based on usage and will continue to offer a free tier.

All this is indeed remarkable, as Ionic team released push support and live updates just few weeks ago. Also, for developers alike, they announced Ionic Market where you’ll be able to make plugins for other users (and, I guess sell them too?). So, IMHO Ionic is building an awesome ecosystem and I bet they’ll become the best hybrid platform! What is left to see is how will the actual price tiers look like.

 

CodeProject, Ionic

Posting data from Ionic app to PHP server

TL;DR

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

The tutorial covering the Ionic version 2 can be found here. The tutorial covering the Ionic version 3 can be found here.

Quickstart

To see it in action:

    1. Clone the finished project from Github
    2. Run ionic serve
  1. You should see something like this:
    ionic_phpDemo

If you want to make it work from your server:

  1. Clone the finished project from Github
  2. Upload the PHP/api.php file to your server
  3. In the www/js/app.js file adjust the link variable to point to your server
  4. Run ionic serve

Step by step on how to create this yourself from scratch

  1. Create a new blank Ionic project with:
    ionic start ionicServerSendTest blank
  2. Copy the following code (you’ll already have the .run() part, the .controller() part is novelty here) in www/js/app.js file:
    // Ionic Starter App
    
    // angular.module is a global place for creating, registering and retrieving Angular modules
    // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
    // the 2nd parameter is an array of 'requires'
    angular.module('starter', ['ionic'])
    
    .run(function($ionicPlatform) {
        $ionicPlatform.ready(function() {
            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            if (window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            }
            if (window.StatusBar) {
                StatusBar.styleDefault();
            }
        });
    })
    
    .controller('AppCtrl', function($scope, $http) {
        $scope.data = {};
    
        $scope.submit = function(){
            var link = 'http://nikola-breznjak.com/_testings/ionicPHP/api.php';
    
            $http.post(link, {username : $scope.data.username}).then(function (res){
                $scope.response = res.data;
            });
        };
    });
  3. On your server, create a 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 (basically an AngularJS app) to your PHP server. The gist is that AngularJS POSTs by default in a JSON format, and thus you have to json_decode  the data that comes to your PHP server.

  4. In www/js/app.js file adjust the link variable to point to the file on your server
  5. In www/index.html file copy the following content:
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
            <title></title>
            <link href="lib/ionic/css/ionic.css" rel="stylesheet">
            <link href="css/style.css" rel="stylesheet">
            <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
            <link href="css/ionic.app.css" rel="stylesheet">
            -->
            <!-- ionic/angularjs js -->
            <script src="lib/ionic/js/ionic.bundle.js"></script>
            <!-- cordova script (this will be a 404 during development) -->
            <script src="cordova.js"></script>
            <!-- your app's js -->
            <script src="js/app.js"></script>
        </head>
        <body ng-app="starter" ng-controller="AppCtrl">
            <ion-pane>
                <ion-header-bar class="bar-stable">
                    <h1 class="title">Ionic Blank Starter</h1>
                </ion-header-bar>
    
                <ion-content padding="true">
                    <form ng-submit="submit()">
                        <label class="item item-input item-stacked-label">
                            <span class="input-label">Username</span>
                            <input type="text" name="username" placeholder="enter username" ng-model="data.username">
                        </label>
    
                        <input class="button button-block button-positive" type="submit" name="submit" value="Submit to server">                    
                    </form>
    
                    <div class="card">
                        <div class="item item-text-wrap">
                            Response: <b ng-bind="response"></b>
                        </div>
                    </div>
                </ion-content>
            </ion-pane>
        </body>
    </html>

    Here you basically created a form with an username input field and with a submit button. Using AngularJS ng-submit you’re saying that once the submit button is clicked AngularJS should handle it within the submit() function which you defined in app.js file before. Input username uses  the ng-model to bind to the variable on the $scope so that you can then use it in your submit() function.

  6. Run ionic serve  from the root directory of your Ionic app (I’m sure you know this, but just in case that’s where the folders like www, plugins, scss reside).
CodeProject, NodeJS

Using PM2 to run your Node.js apps like a pro

Previously I wrote about running Node.js apps with Nodemon and Forever but nowdays I’m using the ever so slightly more professional PM2.

Running your Node.js application by hand is, well, not the way we roll. Imagine restarting the app every time something happens, or god forbid application crashes in the middle of the night and you find about it only in the morning – ah the horror. PM2 solves this by:

  • allowing you to keep applications alive forever
  • reloading applications without downtime
  • facilitating common system admin tasks

To install PM2, run the following command:

sudo npm install pm2 -g

To start your process with PM2, run the following command (once in the root of your application):

pm2 start server.js

As you can see from the output shown on the image below, PM2 automatically assigns an App name (based on the filename, without the .js extension) and a PM2 id. PM2 also maintains other information, such as the PID of the process, its current status, and memory usage.

PM2

As I mentioned before, the application running under PM2 will be restarted automatically if the application crashes or is killed, but an additional step needs to be taken to get the application to launch on system startup (boot or reboot). The command to do that is the following:

pm2 startup ubuntu

The output of this command will instruct you to execute an additional command which will enable the actual startup on boot or reboot. In my case the note for the additional command was:

sudo env PATH=$PATH:/usr/local/bin pm2 startup ubuntu -u nikola

If you want to learn more about the additional PM2 options you can take a look at this post.

Breaking News, Ionic

Ionic Deploy Alpha enables app update on the fly

Yesterday (10.06.2015) Ionic announced the Deploy Alpha which enables you to update your app without having to wait for the review & approval.

They say that

Ionic Deploy lets you update your app on demand for any changes that do not require binary modifications.

You can roll back to a previous version of your app, automatically apply updates, and control every aspect of the upgrade.

Also, the features that they list as upcoming are stunning to say the least:

  • live A/B tests
  • analytics
  • multiple version deployment to certain “Channels”

This is pretty awesome to be honest, and really shows that there is future for Ionic framework and that it’s a great time to be a hybrid app developer.

You can learn more about it from the official blog post.

Angular

ng-wat is the funniest video about Angular you’ll ever see

ng-wat is the most awesome video I’ve seen presented at any official conference. It was presented by the ever so slightly awesome developer Shai Reznik.

Anyways, take a look and see for yourself, and if promise you, you’ll laugh like hell.

The line I like the most is:

Every time you want to complain, make a pull request instead.

Breaking News, Ionic

Ionic has a bright future by partnering with IBM

This is indeed awesome, as it hopefully means that Ionic is here to stay, so that all of us who use it won’t have to fear for it’s future – since it’s all awesome and stuff :). True, this seems more inclined towards business people, but the sole fact that with this more people will know about Ionic and won’t look you strangely when you say you’re developing iOS/Android apps with it by using one codebase.

Some news coverage about this:

  • IBM and Ionic Empower Business Users to Accelerate Mobile App Development
  • Make everyone a hacker: IBM MobileFirst & Ionic empower business users to prototype their own apps
Pluralsight, Three.js

Pluralsight WebGL and Three.js fundamentals course notes

Recently I bought a years worth subscription over at Pluralsight (here’s my portfolio of passed courses), and here I’ll be posting my notes from the courses that I attended. Please note that this is not meant to be as a sort of tutorial, just as the name says – notes for myself :). However, one could get some useful content from these posts as I’m noting things that catch my attention.

Here are my notes from the WebGL and Three.js fundamentals course. I rated the course 4/5 and all in all it’s a good introduction to WebGL with Three.js.

//rant: I passed the exam with the whopping 100%, and actually I feel that since Pluralsight is very famous and all that, that they could improve on the quality (it’s just too easy and does not go into detail) of these certification tests.

var scene = new THREE.Scene(); //acts like a container of all items
var renderer = new THREE.WebGLRenderer(); //how our content will be displayed on the page (WebGL, Canvas or SVG renderers)

It uses a Cartesian cordinate system (x,y,z). If you don’t specify the position- it will be positioned at (0,0,0).

It has a perspective and ortographic camera:

camera = new THREE.PerspectiveCamera(
35, =>fov
window.innerWidth / window.innerHeight,
1, => near
1000 => far planes
);

You can use your dev tools console (Chrome) or Firebug (Firefox) and access items if you properly export the objects in the code (return {scene: scene}); code snippet in the listing below):

//app.js file
var example = (function(){

    "use strict";
    
    var scene=new THREE.Scene(),
    renderer = window.WebGLRenderingContext ? new THREE.WebGLRenderer() : new THREE.CanvasRenderer(),
    light= new THREE.AmbientLight(0xffffff),            
    camera,        
    box;

    function initScene(){
        renderer.setSize( window.innerWidth, window.innerHeight );
        document.getElementById("webgl-container").appendChild(renderer.domElement);

        scene.add(light);
                          
        camera = new THREE.PerspectiveCamera(
        35,
        window.innerWidth / window.innerHeight,
        1,
        1000
        );
                            
        camera.position.z= 100;            
        scene.add( camera ); 

        box = new THREE.Mesh(
        new THREE.BoxGeometry(20,20,20),
        new THREE.MeshBasicMaterial({color: 0x00FF00})
        );

        box.name="box";   

        scene.add(box);

        render();
    }

    function render(){
        box.rotation.y +=0.01;
        
        renderer.render(scene, camera); 
        requestAnimationFrame(render);        
    }

    window.onload = initScene;
    
    return {
        scene: scene
    }

})();
//HTML file
<!DOCTYPE html>

<html>
    <head>
        <title>WebGL with three.js Fundamentals</title>       
    </head>

    <body>
    	<div id="webgl-container"></div>
    	
    	<script src="scripts/three.js"></script><!--DL this from official site-->
    	<script src="scripts/app.js"></script>
    </body>
</html>

Accessing it from Chrome Console as mentioned above:

var a = example.scene.getObjectByName('box');
a.position.x = 10;
a.position.set(0,2,2);
  • Degrees to radians formula: radians = degrees *pi/180
  • Meshes – geometry + material
  • use stats.js
  • different existing controls: FlyControls.js, OrbitControls.js
  • Collision detection
  • Raycasting – returns objects that are on some other objects “ray” and Box3.
  • Physics: PhysiJS is a wrapper for Ammo.js which is a port of C++ Bullet
  • Supports gravity, mass property, friction, restitution (bounciness)

Cool 3D frogger game made by the author: https://github.com/alexmackey/threeJsFrogger

NodeJS

Cannot start OpenDebug because Mono (or a Mono version >= 3.10.0) is required when debugging Node.js applications with free Visual Studio Code on a Mac

This error come up when I tried to use the debugging tools for Node.js program using Visual Studio Code, as outlined in their official tutorial.

The solution was quite easy actually – on a Mac all I had to do was run the following command:

brew install mono
Page 10 of 13« First...«9101112»...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