Friday 27 November 2015

Demo app with Ionic2

Hello,

Like Ionic 1, Ionic 2 apps can be quickly created from the Ionic CLI or GUI tool, or built and tested right in the browser.

To install the latest alpha release, which is currently required for V2 development, run:

# if on linux/osx, run with sudo

npm install -g ionic@alpha

Then we can use the CLI from the command line by running ionic <command>.

Once that’s done, create your first Ionic app:

ionic start cutePuppyPics --v2

To run our app, let’s cd in to the directory that was created, and then run the 
ionic serve command:
cd cutePuppyPics 
ionic serve
Building to a Device

After you have Ionic installed, we can build our app to a physical device. If you
don’t have a physical device on hand, you can still build to a device emulator. 
Check out the iOS simulator docs if you are on Mac, or the Genymotion docs if you
are looking to emulate an Android device. We will also need Cordova to run your appon a native device. To install Cordova, run:
sudo npm install -g cordova
Once you have Cordova installed, and a device or emulator ready to go, we can move on and begin building your app!

Building for Android-

To build for Android, we need to add the Android platform module to Cordova:
ionic platform add android

Next, we will need to install the Android SDK.The Android SDK allows us to build 
compile to a target device running Android. Although the Android SDK comes with a 
stock emulator, Genymotion is recommended since is is much faster. Once installed, we can run an Android image and run:

ionic run android
This application have three tabs namely- Tab1,Tab2 and Tab3.
In which Tab1 has content and you can change the content of Tab1, Tab2 and Tab3.
Thanks...








Load image using ng-src in android ionic aplication with Camera

Hello,

If you want to integrate camera in ionic application, following are the command for that-

ionic start CameraApp blank
cd CameraApp
ionic platform add android
bower install ngCordova
Cordova plugin add https://github.com/apache/cordova-plugin-whitelist.git
cordova plugin add org.apache.cordova.camera



 In your index.html file:-

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <meta http-equiv="Content-Security-Policy" content="default-src *; img-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
    <title></title>
    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>
    <script src="lib/ngCordova/dist/ng-cordova.js"></script>
    <script src="cordova.js"></script>
    <!-- your app's js -->
    <script src="js/app.js"></script>
    <script src="js/controllers/CameraCtrl.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
    <ion-header-bar class="bar bar-header bar-calm">
        <h1 class="title">Camera pic branch ....</h1>
    </ion-header-bar>
    <ion-content ng-controller="CameraCtrl">
        <button class="button button-full button-positive" ng-click="limitPicture()">Take Picture</button>
        <div class="row" ng-repeat="image in images">
        <img ng-src="{{image}}">
        </div>
    </ion-content>
</ion-pane>
</body>
</html>


Here we including the following line of code in head section 

 <meta http-equiv="Content-Security-Policy" content="default-src *; img-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">

Because of following reasons:-

Whitelist functionality is revamped
  • You will need to add the new cordova-plugin-whitelist plugin to continue using a whitelist
  • Setting a Content-Security-Policy (CSP) is now supported and is the recommended way to whitelist.
  • Network requests are blocked by default without the plugin, so install this plugin even to allow all requests, and even if you are using CSP.
  • This new whitelist is enhanced to be more secure and configurable, but the Legacy whitelist behaviour is still available via a separate plugin.
  • Note: while not strictly part of this release, the latest default app created by cordova-cli will include this plugin by default.


In the app.js file add the following line:-

 angular.module('starter', ['ionic', 'ngCordova'])


in the  controller.js file we will add the following lines of code .Here this code also restrict an user to  take only five pics.


.controller("CameraCtrl", function($scope, $cordovaCamera) {
    $scope.images = [];
    $scope.limitPicture = function(){
        if($scope.images.length<5){
            $scope.takePicture();
        }
        else{
            alert("limit exceed");
        }
    }
    $scope.takePicture = function() {
        var options = {
            quality : 75,
            destinationType : Camera.DestinationType.DATA_URL,
            sourceType : Camera.PictureSourceType.CAMERA,
            allowEdit : true,
            encodingType: Camera.EncodingType.JPEG,
            targetWidth: 200,
            targetHeight: 200,
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: false
        };


        $cordovaCamera.getPicture(options).then(function(imageData) {
            var imgURI = "data:image/jpeg;base64," + imageData;
            $scope.images.push(imgURI);
        }, function(err) {
            // An error occured. Show a message to the user
        });
        console.log("length",$scope.images.length);
    }
});



Thanks ...







Thursday 19 November 2015

DeepLink Handler

Hello

Here is a way to handle deeplink if application is not installed in mobile.

Following is the index.html file for handling deeplink-

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1">
    <script type="text/javascript" src="js/deepLinkHandler.js"></script>
    <link rel="stylesheet" href="css/style.css">
    <script type="text/javascript">
        window.onload = function () {
            document.getElementById("url").click();
        }
    </script>
</head>
<body>
<div class="outer">
    <div class="inner">
        <a id="url" href="myapp://" onclick="clickHandler()"></a>
        <img src="../images/default.gif"/>
        <p>
            Redirecting to my app...<br>
            Please wait...
        </p>
    </div>
</div>
</body>
</html>

Where myapp:// is deep link url of my application

Following is the style.css file for handling deeplink-


img {
    top: 35%;
    right: 0;
    left: 0;
    margin: 0 auto;
    vertical-align: middle;
}
.outer{
    display: table;
    width: 100%;
    height: 100vh;
}
.inner{
    text-align: center;
    display: table-cell;
    right: 0;
    left: 0;
    vertical-align: middle;
    margin: 0 auto;
}

and image for the index.html page-


Following is the deepLinkHandler.js file for handling deeplink-

function clickHandler() {
    var isMobile = {
        Android: function() {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function() {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };
    if( isMobile.Android() ) {
alert("Android");
        setTimeout(function(){
            window.location.href = "https://www.google.co.in/";
        }, 5000);
    }
 
    else{
        setTimeout(function(){
            window.location.href = "https://www.google.co.in/";
        }, 5000);
    }
}


Then after deploy your project on heroku.com  and send the project url by email , which is generated by heroku to handle deeplink.



Thanks...

Tuesday 17 November 2015

Deeplinking in Ionic application

Hello,

Deeplinking is a methodology for launching a native mobile application via a link.
Deeplinking connects a unique url to a defined action in a mobile app, seamlessly linking users to relevant content.


Now, we can also use deeplinking in ionic application.

Following are the commands for deeplinking in blank app-

ionic start myapp blank
cd myapp
ionic platform add android

Then we will add the following plugin for the deeplinking

cordova plugin add https://github.com/EddyVerbruggen/LaunchMyApp-PhoneGap-Plugin.git --variable URL_SCHEME=myapp

Here in URL_SCHEME we will assign that name of app which we want in form of url.
So in our case url will be myapp:// 

Now we will add following lines of code in config.xml

<plugin name="cordova-plugin-customurlscheme" source="npm">
    <param name="URL_SCHEME" value="myapp"/>
  </plugin>
Here in value you will assign name as in URL_SCHEME.
So, now your config.xml  looklike-


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<widget id="com.ionicframework.wgldeep641489" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  <name>myapp</name>
  <description>
        An Ionic Framework and Cordova project.
    </description>
  <author email="hi@ionicframework" href="http://ionicframework.com/">
      Ionic Framework Team
    </author>
  <feature name="StatusBar">
    <param name="ios-package" value="CDVStatusBar" onload="true"/>
  </feature>
  <content src="index.html"/>
  <access origin="*"/>
  <preference name="webviewbounce" value="false"/>
  <preference name="UIWebViewBounce" value="false"/>
  <preference name="DisallowOverscroll" value="true"/>
  <preference name="android-minSdkVersion" value="16"/>
  <preference name="BackupWebStorage" value="none"/>
  <preference name="SplashScreen" value="screen"/>
  <preference name="SplashScreenDelay" value="3000"/>
  <plugin name="cordova-plugin-customurlscheme" source="npm">
    <param name="URL_SCHEME" value="myapp"/>
  </plugin>
  <platform name="android">
    <icon src="resources/android/icon/drawable-ldpi-icon.png" density="ldpi"/>
    <icon src="resources/android/icon/drawable-mdpi-icon.png" density="mdpi"/>
    <icon src="resources/android/icon/drawable-hdpi-icon.png" density="hdpi"/>
    <icon src="resources/android/icon/drawable-xhdpi-icon.png" density="xhdpi"/>
    <icon src="resources/android/icon/drawable-xxhdpi-icon.png" density="xxhdpi"/>
    <icon src="resources/android/icon/drawable-xxxhdpi-icon.png" density="xxxhdpi"/>
    <splash src="resources/android/splash/drawable-land-ldpi-screen.png" density="land-ldpi"/>
    <splash src="resources/android/splash/drawable-land-mdpi-screen.png" density="land-mdpi"/>
    <splash src="resources/android/splash/drawable-land-hdpi-screen.png" density="land-hdpi"/>
    <splash src="resources/android/splash/drawable-land-xhdpi-screen.png" density="land-xhdpi"/>
    <splash src="resources/android/splash/drawable-land-xxhdpi-screen.png" density="land-xxhdpi"/>
    <splash src="resources/android/splash/drawable-land-xxxhdpi-screen.png" density="land-xxxhdpi"/>
    <splash src="resources/android/splash/drawable-port-ldpi-screen.png" density="port-ldpi"/>
    <splash src="resources/android/splash/drawable-port-mdpi-screen.png" density="port-mdpi"/>
    <splash src="resources/android/splash/drawable-port-hdpi-screen.png" density="port-hdpi"/>
    <splash src="resources/android/splash/drawable-port-xhdpi-screen.png" density="port-xhdpi"/>
    <splash src="resources/android/splash/drawable-port-xxhdpi-screen.png" density="port-xxhdpi"/>
    <splash src="resources/android/splash/drawable-port-xxxhdpi-screen.png" density="port-xxxhdpi"/>
  </platform>
</widget>


So, now your app will work with the url myapp://




Thanks......

Friday 13 November 2015

$http service in Angularjs

The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.


The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise.


Example-

$http({ 
method: 'GET', 
url: '/demoUrl' 
}) 
.then(function successCallback(response) { 
// this callback will be called asynchronously 
// when the response is available 
}, 
function errorCallback(response) { 
// called asynchronously if an error occurs 
// or server returns response with an error status. 
});

The response object has following properties:
  1. data{string|Object} – The response body transformed with the transform functions.
  2. status{number} – HTTP status code of the response.
  3. headers{function([headerName])} – Header getter function.
  4. config{Object} – The configuration object that was used to generate the request.
  5. statusText{string} – HTTP status text of the response.
A response status code between 200 and 299 is considered a success status and will result in the success callback being called.
If the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the error callback will not be called for such responses.

Example-

post method in $http-

 $http.post(url, data, config)    
        .success(function (data, status, headers, config)
{         // result in case of success
    })        
     .error(function (data, status, header, config) {   
// result in case of error
         });


Friday 6 November 2015

Using promises and $q to handle asynchronous calls in angularjs

Hello,

Here i am introducing how to handle asynchronous calls in angularjs , take a look here-

$q-




  1. - service in module ng

A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

This is an implementation of promises/deferred objects inspired by Kris Kowal's Q.

The CommonJS Promise proposal describes a promise as an interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time.
From the perspective of dealing with error handling, deferred and promise APIs are to asynchronous programming what try, catch and throw keywords are to synchronous programming.


Example-
For the purpose of this example let's assume that variables `$q` and `GetValue`
are available in the current lexical scope (they could have been injected or passed in).

function GetName(name)
var deferred = $q.defer(); 
setTimeout(function() { 
deferred.notify('About to greet ' + name + '.'); 
if (GetValue(name)) { 
 deferred.resolve('Hello, ' + name + '!'); } 

else { 

deferred.reject('Greeting ' + name + ' is not allowed.');  } 

}, 
1000):

return deferred.promise;}var promise = GetName('Robin Hood');

promise.then(function(greeting) {

  alert('Success: ' + greeting);},

function(reason) { 

alert('Failed: ' + reason);},

function(update) { 

 alert('Got notification: ' + update);});





At first it might not be obvious why this extra complexity is worth the trouble. The payoff comes in the way of guarantees that promise and deferred APIs make.

Additionally the promise api allows for composition that is very hard to do with the traditional callback (CPS) approach.

The Deferred API-

A new instance of deferred is constructed by calling $q.defer(). The purpose of the deferred object is to expose the associated Promise instance as well as APIs that can be used for signaling the successful or unsuccessful completion, as well as the status of the task. Methods-
  • resolve(value) – resolves the derived promise with the value. If the value is a rejection constructed via $q.reject, the promise will be rejected instead.
  • reject(reason) – rejects the derived promise with the reason. This is equivalent to resolving it with a rejection constructed via $q.reject.
  • notify(value) - provides updates on the status of the promise's execution. This may be called multiple times before the promise is either resolved or rejected.
Properties-
  • promise – {Promise} – promise object associated with this deferred.

The Promise API-

A new promise instance is created when a deferred instance is created and can be retrieved by calling deferred.promise.
The purpose of the promise object is to allow for interested parties to get access to the result of the deferred task when it completes.
Methods-
  • then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining). It also notifies via the return value of the notifyCallback method. The promise cannot be resolved or rejected from the notifyCallback method.
  • catch(errorCallback) – shorthand for promise.then(null, errorCallback)
  • finally(callback, notifyCallback) – allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved.
Thanks.........