Wednesday, August 29, 2018

Migrating of an existing application from Ionic 3 to 4

Migrating of Ionic 3 Project to Ionic 4


What is ionic: Ionic is an open source UI toolkit for building performant, high-quality mobile and desktop apps using web technologies (HTML, CSS, and JavaScript).

Ionic Framework always focus on frontend user experience. It’s easy to learn and integrates nicely with other libraries or frameworks, such as Angular. Currently, Ionic Framework has official integration with Angular, but its support for Vue and React are in development.

migration from ionic 3 to 4 is very straightforward. 

Migrating from Ionic 3 to 4: You need to follow below steps to migrating an existing application from Ionic 3 to 4.Steps are follows -


Before this please make sure the you have latest version of Node.js and npm are installed on your system.

- First, Install the latest version of Ionic

$ npm install -g ionic

The -g means it is a global install.


- Now create a new project using the blank template -

$ ionic start myApp blank --type=angular


- Project structure : 



- Copy your ionic 3 Angular services from src/providers to src/app/services

Services should include { providedIn: 'root' } in the @Injectable() decorator. For details, please review Angular provider docs. https://angular.io/guide/providers


- Copy the app's other root level items (pipes, components, etc) of your ionic 3, Keep in mind that the project directory structure has been changed from src/components to src/app/components, etc.

- Now copy your ionic 3 global Sass styling from src/app/app.scss to src/global.scss

- Copy the rest of the application, page by page or feature by feature, keeping the following items in mind:

  1. Emulated Shadow DOM is turned on by default.
  2. Page/component Sass should no longer be wrapped in the page/component tag and should use Angular's styleUrls option of the @Component decorator.
  3. RxJS has been updated from v5 to v6.
  4. Certain lifecycle hooks should be replaced by Angular's hooks.


 - Including third-party modules: If your v3 application depends upon third-party modules like moment etc., make sure to install them in the v4 project too.

Breaking Changes: Check this URL for more information (https://github.com/ionic-team/ionic/blob/master/angular/BREAKING.md#breaking-changes)


A list of the breaking changes introduced to each component in Ionic Angular v4 -

Action Sheet
Alert
Back Button
Button
Chip
Colors
Content
Datetime
Dynamic Mode
FAB
Fixed Content
Grid
Icon
Infinite Scroll
Item
Item Divider
Item Options
Item Sliding
Label
List Header
Loading
Menu
Menu Toggle
Modal
Nav
Navbar
Option
Overlays
Radio
Range
Refresher
Scroll
Segment
Select
Spinner
Tabs
Text / Typography
Theming
Toolbar

Wednesday, August 22, 2018

How to check network connection in ionic 2 | ionic 3

Check network availability in ionic 




Why we should use network connection check?
If your app is using internet connectivity then, in this case, this is a very important check. With the help of this plugin, we can find is an internet connection is available on device or not. In this post, we will show an alert of "No Network Connection" if internet connection is not available on the device. This is very easy to implement. Just follow the below steps to implement this :

First, we need to add "Network" plugin in our project by using below command -

$ ionic cordova plugin add cordova-plugin-network-information
$ npm install --save @ionic-native/network

Now add this plugin in your app's module 

import { Network } from '@ionic-native/network';

providers: [
    Network,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]


Now just import plugin on your page where you want to check network connection -

import { Network } from '@ionic-native/network';
import { NavController, AlertController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(private network: Network, public alertCtrl: AlertController,public navCtrl: NavController) {
  if (this.checkNetwork()) {
  // This will call when network avaiable
}
else {
  // This will call when network is not available
  this.showNetworkError();
}
  }

  checkNetwork() {
    if (this.network.type != "none") {
        return true;
    }
    else {
        return false;
    }
  }

 showNetworkError() {
    let alertVar = this.alertCtrl.create({
        title: 'Error!',
        subTitle: 'No Network Connection',
        buttons: ['OK']
    });
    alertVar.present();
 }

}


With the help of above code, you can check network connection in the ionic app. Just check with your app. All the best 👍


If you want to check network connection type, You can check with the help of the below function

    checkNetwork() {
        this.platform.ready().then(() => {
            var networkState = this.network.type;
            var states = {};
            states[Connection.UNKNOWN]  = 'Unknown connection';
            states[Connection.ETHERNET] = 'Ethernet connection';
            states[Connection.WIFI]     = 'WiFi connection';
            states[Connection.CELL_2G]  = 'Cell 2G connection';
            states[Connection.CELL_3G]  = 'Cell 3G connection';
            states[Connection.CELL_4G]  = 'Cell 4G connection';
            states[Connection.CELL]     = 'Cell generic connection';
            states[Connection.NONE]     = 'No network connection';
            let alertVar = this.alertCtrl.create({
                title: "Connection Status",
                subTitle: states[networkState],
                buttons: ["OK"]
            });
            alertVar.present();
        });
    }


We can also subscribe network connect check, With this, we can manage network state changes (Online / Offline) at the same time -

import { Network } from '@ionic-native/network';

constructor(private network: Network) { }



Check below code to watch the network connection -

// watch the network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
  console.log('network connected!');
  // We just got a connection
  setTimeout(() => {
    if (this.network.type === 'wifi') {
      console.log('we got a wifi connection, woohoo!');
    }
  }, 3000);
});


// watch the network for a disconnect
let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
  console.log('network was disconnected :-(');
});


// stop connect watch
connectSubscription.unsubscribe();

// stop disconnect watch
disconnectSubscription.unsubscribe();

Sunday, August 19, 2018

How to get YouTube video thumbnail from the YouTube video ID?



How to get YouTube video thumbnail from the YouTube video ID | get a YouTube video thumbnail from the YouTube API | How we can use the YouTube Video ID to Retrieve the Video Thumbnails

As we know each YouTube video has thumbnail images. So here is a quick and very simple tip to get thumbnail images with the help of youtube video id.   


http://img.youtube.com/vi/[your-youtube-video-id]/0.jpg
http://img.youtube.com/vi/[your-youtube-video-id]/1.jpg
http://img.youtube.com/vi/[your-youtube-video-id]/2.jpg
http://img.youtube.com/vi/[your-youtube-video-id]/3.jpg


We have some other options, Please check below examples -


The default thumbnail image is:
http://img.youtube.com/vi/[your-youtube-video-id]/default.jpg

For the high-quality thumbnail:
http://img.youtube.com/vi/[your-youtube-video-id]/hqdefault.jpg

For medium quality thumbnail:
http://img.youtube.com/vi/[your-youtube-video-id]/mqdefault.jpg

For standard definition thumbnail:
http://img.youtube.com/vi/[your-youtube-video-id]/sddefault.jpg

For maximum resolution thumbnail:
http://img.youtube.com/vi/[your-youtube-video-id]/maxresdefault.jpg


What is my Video ID: This is very simple to find YouTube video ID. First, open youtube and go to the YouTube video. Now, Look at the URL of that video, at the end of URL, you can see a combination of numbers and letters after an equal sign (=). This is the video id for that video. Please check id in below image :




Thursday, August 16, 2018

Get user current location in ionic 2 | ionic 3

Get Geolocation (Latitude and Longitude) in Ionic 2 -






In this post, We will learn, how to get the user current latitude and longitude using the Geolocation native plugin (Ionic Plugin).

Geolocation : Geolocation is the identification of the real world geographic location of an object. Geolocation works through a pre-built GPS in a device. This provide location in the form of latitude and longitude of device.


Now, We are going to create a code flow for this. This is very simple to use.

Step 1: Install Geolocation plugin in your project by using below command -

ionic cordova plugin add cordova-plugin-geolocation
npm install --save @ionic-native/geolocation

For iOS platform you have to add below lines in project configuration.xml file -

<edit-config file="*-Info.plist" mode="merge" 
target="NSLocationWhenInUseUsageDescription"> <string>This app required to access your device location.</string> </edit-config>


Step 2 : Now add this plugin to your app's module (app.module.ts) -

import { Geolocation } from '@ionic-native/geolocation';

Add "Geolocation" in providers -

 providers: [
    Geolocation,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]


Step 3 : Now use below code in your TS file where you want to use this plugin -

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

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  public latitude:any;
  public longitude:any;

  constructor(public navCtrl: NavController, private geolocation: Geolocation) {

  }

  getLocation()
  {
    this.geolocation.getCurrentPosition().then((resp) => {
       this.latitude=resp.coords.latitude;
       this.longitude=resp.coords.longitude;
    }).catch((error) => {
      console.log('Error getting location'+JSON.stringify(error));
    });
  }


}

Step 4 : Use below code in your HTML file -
<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Geolocation Example</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding class="login">

  <h3>Current Latitude: {{latitude}}</h3>
  <h3>Current Longitude: {{longitude}}</h3>
  <button ion-button full primary (click)="getLocation()">Get Location</button>

</ion-content>



This is done from code side. All the best 👍

Wednesday, August 1, 2018

Contact us form in php

Contact us form in php

In this post we will learn below functionality :

1. HTML UI of contact us page.
2. HTML validations.
3. Manage CSS.
4. Email all details on our email id.

1. HTML UI of contact us page: Here is the example of basic HTML form for contact us page.


   
      <h2>Contact Form</h2>
<form id="form" method="post" action="contact_us.php">
    <fieldset>
      <label><input name="name" id="name" placeholder="Name*" required type="text"></label>
      <label><input name="email" id="email" required type="email" placeholder="Email*"></label>
      <label><input name="phone_no" required type="text" placeholder="Phone*"></label>
      <label><textarea name="query" required placeholder="Message*"></textarea></label>
      <div class="btns">
        <input class="send-btn" type="submit" value="Send" name="">
      </div>
    </fieldset>  
</form>
   
 

Here,
method="post" (To post data on the server by POST method)
action="contact_us.php" (Form data will post on contact_us.php page)




2. HTML validations : Below are the HTML 5 validations which we used in HTML form  
required (This is the required validation of HTML 5)
required type="email" (This is for required with valid email address)


3. Manage CSS: Use below CSS to style your submit button 

.send-btn{
width:100%;
height:30px;
margin-bottom:10px;
background-color: #ff9000;
color: #fff;
border-radius: 10px;
}

4. Email all details on our email id: Create a contact_us.php file and add below code in this file 


$tryAgainUrl="<a href='contacts.html'>Try Again</a>";
if(!empty($_POST))
{
if( $_POST['name'] && $_POST['query'] && $_POST['phone_no'] && $_POST['email'])
{
$name=$_POST['name'];
$query=$_POST['query'];
$phone_no=$_POST['phone_no'];

/* email send code start */
$from="info@yourdomain.com";
$to="support@yourdomain.com";
$email=$_POST['email'];
$subject = 'Contact us query';
$message ="Name : ".$name."\r\n\r\n";
$message.="Email : ".$email."\r\n\r\n";
$message.="Phone No :- ".$phone_no."\r\n\r\n";
$message.="Message :- ".$query."\r\n\r\n";

$headers = "From: $from\r\nReply-to: $email";
$sent = mail($to, $subject, $message, $headers);
/* email send code end */

header("Location: contacts.html"); /* Redirect browser */
exit();
}else{
echo "Invalid Details. ".$tryAgainUrl;
}
}else{
echo "Invalid Details. ".$tryAgainUrl;
}
?>


Here :
mail(to,subject,message,headers);

$to = This is required. (Receiver email address)
$subject = This is required. (Subject of the email)
$message = This is required. (Defines the message to be sent) 
$headers = This is Optional. (Specifies additional headers, like From, Cc, and Bcc)