RSS

Setting Maximum Character Limit & Numeric Validation in UITextField

Setting Maximum Character Limit in UITextField

We can’t directly set the maximum length to the UITextField because it’s class has no max length property, But it can be achieved by using the following text field delegate method.

#define MAX_LENGTH 20

 – (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

NSUInteger newLength = [textField.text length] + [string length] – range.length;

if(newLength > MAX_LENGTH){

         return NO;
       }
       else{
                return YES;
       }
}
Before the text field changes, the UITextField asks the delegate if the specified text should be changed. The text field has not changed at this point, so we grab it’s current length and the string length we’re inserting, minus the range length. If this value is too long (more than 20 characters in this example), return NO to prohibit the change.

Numeric Validation in UITextField

#define NUMBERS_ONLY 0123456789

– (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string 

{
if([textField isEqual:txtPhone])
{
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
        NSString *filteredstring  = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@””];
        return ([string isEqualToString:filteredstring]);
}
       return  TRUE;
}
 
Leave a comment

Posted by on February 12, 2013 in iOS

 

Tags: , , , , , , , , , ,

Generating barcode using php

This post will walk through the basics of barcode and the process of  generating the bar code using php.

What is a Bar Code?

Bar-coding is one of the AIDC (Automatic Identification and Data Collection)technologies which reduce human involvement in data entry and collection and So it used to reduce error and time. Barcodes are structured to contain specific product related information. It basically encodes alphanumeric characters and symbols using Series of black bars and white spaces of varying widths are printed on labels to uniquely identify items. 

How does a barcode work?

A barcode essentially is a way to encode information in a visual pattern that a machine can read. The combination of black and white bars (elements) represents different text characters which follows a set algorithm for that barcode type. The barcodes are read with a special optical scanner, which measures reflected light and interprets the code into numbers and letters that are passed on to a computer.Nowadays bar code readers are also available on devices including desktop printers and smartphones.

 1D (linear) & 2D barcode:

One-dimensional (1D) bar codes represented data by varying the widths and spacing of parallel lines. There are several versions of 1D codes and some encode only numbers while others can encode any keyboard character. All the information in the code is organized horizontally from left to right. These types of codes can be read by any type of barcode scanner.

2D bar codes use a variety of symbols like rectangles, dots, hexagons and other geometric patterns, they are generally referred to as bar codes as well. It  organize information vertically and horizontally. This allows 2D codes to hold much more information and take up less space than a 1D code. 2D codes require an imager scanner to be read properly.

One Dimensional (1D) Barcode:

image

Two dimensional (2D) Barcode:


Characters limitation in barcode

Depending on the specific barcode type, 1D barcodes can have from 20-25 characters while 2D codes go up to 2,000 characters. The main practical concern is that as you increase the amount of information in the barcode the bigger it will become. This is especially the case with 1D barcodes and in use most people encode 8-15 characters.

Types of Barcode:

The following are some of the most familiar barcode formats used in application.

  • standard 2 of 5 (std25)
  • interleaved 2 of 5 (int25)
  • ean 8 (ean8)
  • ean 13 (ean13)
  • upc (upc)
  • code 11 (code11)
  • code 39 (code39)
  • code 93 (code93)
  • code 128 (code128)
  • codabar (codabar)
  • msi (msi)
  • datamatrix (datamatrix)

Generating Barcode using PHP:

Generating barcodes with PHP is became very simple with the free Open source PHP Barcode Coder library.

Download the library and include the php-barcode.php class in your php file as like including the other files.

By using this class you can generate the following types of  barcode.

  • Barcode
  • BarcodeI25
  • BarcodeEAN
  • BarcodeMSI
  • Barcode11
  • Barcode39
  • Barcode93
  • Barcode128
  • BarcodeCodabar
  • BarcodeDatamatrix

It also provide the options to generate the barcode either in pdf format or image format by using the static functions as given below

  1. Barcode::gd($res, $color, $x, $y, $angle, $type, $datas, $width = null, $height = null);
  2. Barcode::fpdf($res, $color, $x, $y, $angle, $type, $datas, $width = null, $height = null);

Barcode::gd is used to generate the barcode as a image file.

Barcode::fpdf is used to generate the barcode as a PDF file.

$x, $y (numeric)– used to represent the barcode center.

$angle(numeric)– represents the rotation of angle in degree.

$datas- string

Value barcode (dependent on the type of barcode)
If barcode type include it, the presence of the checksum is not mandatory, it ise automatically recalculated

array

type : ean8, ean13, code11, code39, code128, codabar
member Type
code string
type : std25, int25, code93
member Type
code string
crc boolean
type : msi
member Type
code string
crc boolean
array crc1 : string(“mod10”, “mod11”)
crc2 : string(“mod10”, “mod11”)
type : datamatrix
member Type
code string
rect boolean (default : false)

type (string) – the value of type should be one of the following formats.

  • codabar
  • code11 (code 11)
  • code39 (code 39)
  • code93 (code 93)
  • code128 (code 128)
  • ean8 (ean 8)
  • ean13 (ean 13)
  • std25 (standard 2 of 5 – industrial 2 of 5)
  • int25 (interleaved 2 of 5)
  • msi
  • datamatrix (ASCII + extended)

$width, $height – Used to represent the width and height of the barcode. For 2D barcode(datamatrix) $height is not used.

Example

In this example, I am using code 128 format and generating the barcode in image format.

<?php

  include(‘../php-barcode.php’);
 
  $fontSize = 10; // GD1 in px ; GD2 in point
  $marge = 10; // between barcode and hri in pixel
  $x = 125;  // barcode center
  $y = 125;  // barcode center
  $height = 50;  // barcode height in 1D ; module size in 2D
  $width = 2;  // barcode height in 1D ; not use in 2D
  $angle = 90; // rotation in degrees 
  $code = ‘pradeep’; // barcode, of course 😉
  $type = ‘code128’;
  
  // ————————————————– //
  // ALLOCATE GD RESSOURCE
  // ————————————————– //
  $im = imagecreatetruecolor(300, 300);
  $black = ImageColorAllocate($im,0x00,0x00,0x00);
  $white = ImageColorAllocate($im,0xff,0xff,0xff);
  imagefilledrectangle($im, 0, 0, 300, 300, $white);
  
  // ————————————————– //
  // GENERATE
  // ————————————————– //
  $data = Barcode::gd($im, $black, $x, $y, $angle, $type,   array(‘code’=>$code), $width, $height);
  header(‘Content-type: image/gif’);
  imagegif($im);
  imagedestroy($im);
?>
Output of the above file will be look like this:
image

That’s it. Hope you find this tutorial helpful!!. Thank you!!!
 
 
4 Comments

Posted by on January 29, 2013 in General, PHP

 

Tags: , , , , , , , , , , ,

Apple – Specific Meta Tags & links for mobile web application

This post will describe about apple specific meta tags, links tags and when and how to use it in your website or mobile web application.

Introduction

The <meta> tag  are used to provide additional information (Metadata)  about the web page, most often to help search engines categorize them correctly when indexing. They are inserted into the Head section of the HTML document, but the information stored in the meta tag isn’t visible to a user visiting the site but it can be used by search engines & browsers to display content or reload page.

Usage of Meta Tags

Meta elements are typically used to specify page description, keywords, the content language, author of the document, last modified,technical formats,pointers to other files such as News Feeds and Fav icons and any other metadata not provided through the other head elements and attributes.

The following are some of the most important operations that we can done by using meta tags in iOS devices:

Enable Full Screen
It is used to set whether a web application runs in full-screen mode.

< meta name=”apple-mobile-web-app-capable” content=”yes”>

If content is set to yes, the web application runs in full-screen mode; otherwise, it does not.

Note:The content attribute must be defined if the name or the http-equiv attribute is defined. if none of these are defined, the content attribute cannot be defined.

Setting Status Bar Style

It is used to set the style of the status bar for a web application in iOS.

< meta name=”apple-mobile-web-app-status-bar-style” content=”default”>

1) If you specify content as default, the status bar appears normal.

2) If you specify content as black, the status bar appears in black color.

3) If you specify content as black-translucent, the web content is partially obscured by the status bar and it appears in black color and translucent.

Phone number detection:

By default, Safari on iOS detects any string formatted like a phone number and makes it a link that calls the number.

You can enable or disable the  automatic detection of phone numbers in iOS safari  by using the following meta tag in your html file.

< meta name=”format-detection” content=”telephone=no”>

By giving telephone=no, to disable this feature and yes to enable this feature.

Changing viewport size:

Viewport meta key is used to set the width and height of the viewport. It is used to improve the presentation of page while displaying  on iOS.

Viewport meta key has supported the following six properties.

1) width :used to specify width of the viewport in pixels.

< meta name = “viewport” content = “width = device-width”>

device-width represents the width of the device in pixels.

2) height: used to specify height of the viewport in pixels.

3) initial-scale:  used to specify initial scale of the viewport.

< meta name = “viewport” content = “initial-scale = 1.0”>

4) minimum-scale: Specifies the minimum scale value of the viewport. The default is 0.25. The range is from >0 to 10.0.

5) maximum-scale: Specifies the maximum scale value of the viewport. The default is 5.0. The range is from >0 to 10.0.

6) user-scalable: Determines whether or not the user can zoom in and out.Set to yes to allow scaling and no to disallow scaling. The default is yes.

< meta name = “viewport” content = “width = 320, initial-scale = 2.3, user-scalable = no”>

Link Tags for Homescreen Icons

Apple provide the option to users to  save the page to home screen, While browsing online with safari an Apple device like iPhone, iPad, and iPod touch. This option is  used to access that page without having to launch their browser. By default, Apple will use the screen shot of the web page when creating a home screen icon, which often looks like a white square.

Apple also provided a option for site owners to  use their custom icon instead.

It can be achieved by using Apple touch icon. It is  very similar to favicon for Apple mobile devices. So you can set an Apple Touch Icon for your website just like you can set a favorite icon.

There are two kind of icons:

1)Icon with Glossy effect (Standrand Icon)

To use a standard icon, add the following link tag  into the head section of your website

< link rel=”apple-touch-icon” href=”” />

2)Icon without Glossy effect (Precomposed Icon)

To use a precomposed icon, add the following link tag into the head section of your website

< link rel=”apple-touch-icon-precomposed” href=”” />

To include the different size of  apple touch icon:

< link rel=”apple-touch-icon-precomposed” sizes=”72×72″ href=”” />
< link rel=”apple-touch-icon-precomposed” sizes=”114×114″ href=”” />
< link rel=”apple-touch-icon-precomposed” sizes=”144×144″ href=”” />
< link rel=”apple-touch-icon-precomposed” sizes=”512×512″ href=”” />
< link rel=”apple-touch-icon-precomposed” sizes=”1024×1024″ href=”” />

Link Tag  for Startup image (Splash screen):

splash screen is an image that appears while page or program is loading. It may also be used to describe an introduction page on a website.

To implement the startup page in your website add the following link tag in your head section.

<link rel=”apple-touch-startup-image” href=”../startup.png” />

To include the Startup image with various sizes:

<!– iPhone –>

<link rel=”apple-touch-startup-image”  media=”(device-width: 320px)”

href=”apple-touch-startup-image-320×460.png”>

<!– iPhone (Retina) –>

<link rel=”apple-touch-startup-image”  media=”(device-width: 320px)

and (-webkit-device-pixel-ratio: 2)”  href=”apple-touch-startup-image-640×920.png”>

<!– iPad (portrait) –>

<link rel=”apple-touch-startup-image” media=”(device-width: 768px)

and (orientation: portrait)” href=”apple-touch-startup-image-768×1004.png”>

<!– iPad (landscape) –>

<link rel=”apple-touch-startup-image” media=”(device-width: 768px)

and (orientation: landscape)” href=”apple-touch-startup-image-748×1024.png”>

<!– iPad (Retina, portrait) –>

<link rel=”apple-touch-startup-image” media=”(device-width: 768px)

and (orientation: portrait) and (-webkit-device-pixel-ratio: 2)”

href=”apple-touch-startup-image-1536×2008.png”>

<!– iPad (Retina, landscape) –>

<link rel=”apple-touch-startup-image” media=”(device-width: 768px)

and (orientation: landscape) and (-webkit-device-pixel-ratio: 2)”

href=”apple-touch-startup-image-1496×2048.png”>

I hope this post will helpful for you.Thanks for your time.

Share it with your friends!

 
15 Comments

Posted by on January 18, 2013 in General, HTML5, iOS, Sencha Touch

 

Tags: , , , , , , , , , , , , , , ,

How to create repositories in GitHub?

This post will walk you through the process of creating  a repository on GitHub, then adding files, committed, and pushed it to GitHub repository.

What is meant by GitHub?

GitHub is a web-based hosting service for software development projects that use the Gitrevision control system. GitHub offers both paid plans for private repositories, and free accounts for open source projects.

This service provides free public repositories, issue tracking, graphs, code review, downloads, wikis, collaborator management, and more. There are also social networking elements of the service including feeds, the ability to follow other users, and network related graphs.

Sign up for a GitHub account, if you don’t already have one.

image1

Go to the GitHub login page and log in using the email and password associated with your account.

image2

Make a new repo on GitHub

Every time you make a commit with Git, it is stored in a repository. To put your project files up on GitHub, you’ll need to have a GitHub repository.

Click the create repository icon or click the “New Repository” button in the “Your Repositories” pane on right side of the page.

image3

Fill out the information on this page. When you’re done, click “Create Repository.”

image4

Select the “public” option to create a free public repo that anyone can access, or select the “private” & “Upgrade my account” option to upgrade to a paid account and create a private repository.

image5That’s it! You have successfully created your first repo!

Then follow the steps given below to upload your project files to your repository from your local system.

Step 1: Initialized  Git repository

Open the command prompt and type the following code:

# Creates a directory for your project called “Hello_World” in your user directory

mkdir ~/Hello_World

# Changes the current working directory to your newly created directory

cd ~/Hello_World

# Initialized empty Git repository in /Hello-World/.git/

git init

# Creates a file called “README” in your Hello_World directory

 touch README

It will create a  README file  in your Hello_World directory.
image6

Step 2:Adding  & Committing your files to Git repo

Now that you have your files set up, it’s time to commit it. A commit is essentially a snapshot of all the files in your project at a particular point in time. In the command prompt, type the following code:

To Add all files to the list of files to be committed use the below command

git add .

(or)

If you want add only a specific file to the list of files to be committed. Add like this

git add filename

Then commits your added files with your comments “initial commit”

git commit -m ‘initial commit’

Step 3: Creates a remote named “origin” pointing at your GitHub repo

To connect your local repository to your GitHub account, you will need to set a remote for your repo and push your commits to it:

git remote add origin https://github.com/username/Hello_World.git

or

git remote add origin git@github.com:username/Hello_World.git

Step 4: Push your commit in the “master” branch to GitHub

git push origin master

Now if you look at your repository on GitHub, you will see your project files has been added to it.

image12

That’s it!

 
4 Comments

Posted by on January 13, 2013 in General

 

Tags: , , , , ,

Updating and displaying user current location in Sencha touch map

This post describes about  getting an user current location either by  manually or automatically and displaying it in a map in sencha touch based mobile application.

To use the map component in sencha touch application. you must include an additional JavaScript file in your index.html from Google:

<script type=”text/javascript” src=”http://maps.google.com/maps/api/js?sensor=true”></script&gt;

Add a map to the viewport:
Ext.Viewport.add({

xtype: ‘map’,
id:’geomap’

});


Updating and displaying user current location in map:

The current location of the user is obtained by using the geolocation utility of sencha touch framework. It provides a cross browser class for retrieving location information.

var geo = Ext.create(‘Ext.util.Geolocation’, {

autoUpdate: true,

frequency: ‘10000’,

listeners: {
locationupdate: function (geo) {

var center = new google.maps.LatLng(geo.getLatitude(), geo.getLongitude());

Ext.getCmp(‘geomap’).update(center);

//To place the marker

var marker = new google.maps.Marker({
position: center,
map: Ext.getCmp(‘geomap’).map
});

alert(‘New latitude: ‘ + geo.getLatitude());

},

locationerror: function (geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) {

if (bTimeout) {
alert(‘Timeout occurred.’);
} else {
alert(‘Error occurred.’);
}

}

}

});

If you set  autoUpdate property to true. It  will frequently check the user location and  firing a location update event immediately when new location information is available.

The frequency property  denotes the frequency of  each update  if autoUpdate property is set to true. The default value of frequency is 10000.

But if you update the location very frequently,  it will affect your device battery performance. So it is better to set this property to false and update the location when we actually needed it by using geo.updatelocation()

var geo = Ext.create(‘Ext.util.Geolocation’, {

autoUpdate: false,

listeners: {
locationupdate: function (geo) {

var center = new google.maps.LatLng(geo.getLatitude(), geo.getLongitude());

Ext.getCmp(‘geomap’).update(center);

//To place the marker

var marker = new google.maps.Marker({
position: center,
map: Ext.getCmp(‘geomap’).map
});

alert(‘New latitude: ‘ + geo.getLatitude());

},

locationerror: function (geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) {

if (bTimeout) {
alert(‘Timeout occurred.’);
} else {
alert(‘Error occurred.’);
}

}

}

});
geo.updateLocation();

When geo.updatelocation() is called,it immediately begins tracking the user current location information, firing a locationupdate event when new location information is available.

A locationerror event is raised when an error occurs retrieving the location, either due to a user denying the application access to it, or the browser not supporting it.

 
3 Comments

Posted by on January 12, 2013 in HTML5, PhoneGap, Sencha Touch

 

Tags: , , , , , , , , ,

How to get Latitude/Longitude from an address?

This post describes about an easy way to get Latitude/Longitude from an address and getting address of the current location by using Google Geocoding API. Google Geocoding API provides a direct way to access these services via an HTTP request.

Getting Lat,Long values based on Address:

This is achieved by using geocoding.The term geocoding generally refers to translating a human-readable address into a location on a map.

A Geocoding API request must be of the following form:

http://maps.googleapis.com/maps/api/geocode/output?parameters

where output may be either of the following values:

  • json (recommended) indicates output in JavaScript Object Notation (JSON)
  • xml indicates output as XML

//call this google api to get the latitude and longitude by passing the address

http://maps.googleapis.com/maps/api/geocode/json?address=%20Coimbatore,%20Tamil%20Nadu,%20India&sensor=false

sensor in the above url indicates whether or not the geocoding request comes from a device with a location sensor. This value must be either true or false.

You will get the result like this

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Coimbatore",
               "short_name" : "Coimbatore",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Coimbatore",
               "short_name" : "Coimbatore",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Tamil Nadu",
               "short_name" : "TN",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Coimbatore, Tamil Nadu, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 11.14356120,
                  "lng" : 77.1133590
               },
               "southwest" : {
                  "lat" : 10.89792370,
                  "lng" : 76.8830110
               }
            },
            "location" : {
               "lat" : 11.01684450,
               "lng" : 76.95583209999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 11.09502970,
                  "lng" : 77.05123890
               },
               "southwest" : {
                  "lat" : 10.89792370,
                  "lng" : 76.8830110
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

If you want the result in xml format then replace the json with xml in the above url

http://maps.googleapis.com/maps/api/geocode/xml?address=%20Coimbatore,%20Tamil%20Nadu,%20India&sensor=false

You will get the latitude value of the given address by getting the value  of geometry->location->lat from the above result.

and You will get the longitude value of the given address by getting the value  of  geometry->location->lng from the above result.

Getting Address of the location based on lat,long:

This can be achieved by using reverse geocoding.

The process of doing the converse, translating a location on the map into a human-readable address, is known as reverse geocoding.

By passing the lat,lng value in thelatlng parameter of Google geocode api will give you a address corresponding to that.

http://maps.googleapis.com/maps/api/geocode/json?latlng=11.0086005,76.9502163&sensor=true

You will get the result like this

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "West Sambandam Road",
               "short_name" : "West Sambandam Road",
               "types" : [ "route" ]
            },
            {
               "long_name" : "R.S. Puram",
               "short_name" : "R.S. Puram",
               "types" : [ "sublocality", "political" ]
            },
            {
               "long_name" : "Coimbatore",
               "short_name" : "Coimbatore",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Coimbatore",
               "short_name" : "Coimbatore",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Tamil Nadu",
               "short_name" : "TN",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "641002",
               "short_name" : "641002",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "West Sambandam Road, R.S. Puram, Coimbatore, Tamil Nadu 641002, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 11.00864560,
                  "lng" : 76.9506840
               },
               "southwest" : {
                  "lat" : 11.00832450,
                  "lng" : 76.94864410
               }
            },
            "location" : {
               "lat" : 11.0084830,
               "lng" : 76.94966440
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 11.00983403029150,
                  "lng" : 76.95101303029149
               },
               "southwest" : {
                  "lat" : 11.00713606970850,
                  "lng" : 76.94831506970849
               }
            }
         },
         "types" : [ "route" ]
      },
......

Note that the reverse geocoder returned more than one result. Generally, addresses are returned from most specific to least specific; the more exact address is the most prominent result, as it is in this case. Note that it return different types of addresses, from the most specific street address to less specific political entities such as neighborhoods, cities, counties, states, etc. If you wish to match a more general address, you may wish to inspect the "types" field of the returned Placemarks.

The result’s "formatted_addresses"  represents the geographically name a location not a postal address.

Note: Reverse geocoding is an estimate. The geocoder will attempt to find the closest addressable location within a certain tolerance; if no match is found, the geocoder will return zero results.

 
Leave a comment

Posted by on January 5, 2013 in General

 

Tags: , , , , , , , , ,

Automatically showing & hiding a LoadMask for every Ajax request made in Sencha Touch 2

This post describes an easy way to show and hide a Load Mask  automatically for every Ajax request made in Sencha Touch 2 based application.

Usually, Load mask is used to indicate the user  that something was happening in the background and also it prevents the user action until the application finished the current process.

loadingexample

It is achieved in the sencha touch based application by simply Adding the mask to the Viewport  in the beforerequest event of ajax control  and removing it in the requestcompleterequestexception event of ajax control.

//Fires before a network request is made to retrieve a data object.

Ext.Ajax.on(‘beforerequest’, function (con, opt) {

        //To show the mask

Ext.Viewport.setMasked({
xtype: ‘loadmask’,
message: ‘Please wait…’,
indicator: true
});

}, this);

//Fires if the request was successfully completed and hide the mask.
Ext.Ajax.on(‘requestcomplete’, function (con, res, opt) {

         //To hide the mask

Ext.Viewport.setMasked(false);

}, this);

//Fires if an error HTTP status was returned from the server  and hide the mask.
Ext.Ajax.on(‘requestexception’, function (con, response, opt) {

         //To hide the mask

Ext.Viewport.setMasked(false);

}, this);

So it will display the load mask once the request is made and hiding the mask once the request is completed or received an error status automatically.

That’s it.

 
21 Comments

Posted by on January 2, 2013 in iOS, Sencha Touch

 

Tags: , , , ,

Capturing and uploading an image to the web server in phonegap based application

This tutorial is about Capturing an image (either taking a new picture by using device camera or pick the photos already in the photo gallery) and Uploading it to a web server by using Phonegap JavaScript API in the Phonegap based ios and android application.

Before we entered into the code. we need to have a set of permission to access the device camera.

Follow the steps given below to set the permissions for accessing a device camera.
Android:

Step 1 : Add the camera plugin in app/res/xml/plugins.xml file

plugin name=”Camera” value=”org.apache.cordova.CameraLauncher”

Step 2 : Add the following permission in Android Manifest file
uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”

iOS:

Add the CDVCamera plugin in the plugins option of Cordova.plist file located in App/Supporting Files.

Add the following functions in your index.html

var pictureSource; // picture source
var destinationType; // sets the format of returned value

// Wait for Cordova to connect with the device
document.addEventListener(“deviceready”,onDeviceReady,false);

// Cordova is ready to be used!
function onDeviceReady()
{

pictureSource=navigator.camera.PictureSourceType; destinationType=navigator.camera.DestinationType;
}

// Called when a photo is successfully retrieved
function onPhotoURISuccess(imageURI) {
options = new FileUploadOptions();

// parameter name of file:

options.fileKey = “my_image”;

// name of the file:

options.fileName = imageURI.substr(imageURI.lastIndexOf(‘/’) + 1);

// mime type:

options.mimeType = “text/plain”;

params = { val1: “some value”, val2: “some other value” };

options.params = params;

ft = new FileTransfer();

ft.upload(imageURI, “http://example.com/upload.php&#8221;, success, fail, options);

}

function success(message) {
alert(‘Your photo uploaded successfully.’);
}

function fail(message) {
alert(‘Failed because: ‘ + message);
}

function getPhoto(source) {

// Retrieve image file location from specified source navigator.camera.getPicture(onPhotoURISuccess, onFail, {

quality: 50, destinationType: destinationType.FILE_URI, sourceType: source });

}
function onFail(message) {

alert(‘Failed because: ‘ + message);

}

To get the picture from gallery call the getPhoto function like this

getPhoto(pictureSource.SAVEDPHOTOALBUM );

To take a new picture by using camera call the getPhoto function like this

getPhoto(pictureSource.CAMERA );

The navigator.camera.getPicture function in the PhoneGap takes three arguments. The first argument is a success callback, the second argument is a failure callback, and the third argument is an object containing options.

  • destinationType:  It has two values
  • Camera.DestinationType.FILE_URI – (it returns uri of the photo on disk)
  • Camera.DestinationType.DATA_URL – (it returns image data in base64 format)
  • sourceType: It has two values
  • To get a picture from gallery give source type as Camera.PictureSourceType.SAVEDPHOTOALBUM
  • To get a new picture using camera give source type as Camera.PictureSourceType.CAMERA

(Note: The image quality of pictures taken using the camera on newer devices is quite good, and images from the Photo Album will not be downscaled to a lower quality, even if a quality parameter is specified. Encoding such images using Base64 has caused memory issues on many newer devices. Therefore, using FILEURI as the ‘Camera.destinationType’ is highly recommended.)

When a photo is successfully captured, the onPhotoURISuccess function will be called. This function will be passed the imageURI of the photo on disk.

Then upload the captured photo to the webserver by using the upload function of file transfer object in phonegap.

The upload function takes imageURI as a first arugment & upload url as a second argument.

The third and fourth parameter of upload function contains the success and failure callback function respectively.

The fifth argument is an object containing any extra parameters you want to send to the server.

The upload.php file in the webserver will look like this:

//if the file is uploaded.
if($_FILES[‘photo’][‘name’])
{
//if no errors…
if(!$_FILES[‘photo’][‘error’])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES[‘photo’][‘tmp_name’]); //rename file
if($_FILES[‘photo’][‘size’] > (1024000)) //can’t be larger than 1 MB
{
$valid_file = false;
$message = ‘Oops! Your file\’s size is to large.’;
}

//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES[‘photo’][‘tmp_name’], ‘uploads/’.$new_file_name);
$message = ‘Congratulations! Your file was accepted.’;
}
}
//if there is an error…
else
{
//set that to be the returned message
$message = ‘Ooops! Your upload triggered the following error: ‘.$_FILES[‘photo’][‘error’];
}
}

//you get the following information for each file:
$_FILES[‘field_name’][‘name’] //represents the name of file uploaded
$_FILES[‘field_name’][‘size’]   //represents the size of file uploaded
$_FILES[‘field_name’][‘type’] //represents the mime type of file uploaded
$_FILES[‘field_name’][‘tmp_name’]

Conculsion

By using the above files, you can successfully capturing and uploading the picture to the webserver  either by accessing the gallery or camera in a device  in PhoneGap based ios and android applications.

 
3 Comments

Posted by on January 2, 2013 in HTML5, iOS, PhoneGap, Sencha Touch

 

How to Create an IPA file In Xcode 4.3 or higher?

What is meant by IPA?

IPA stands for  iPhone application archive which stores an iPhone app. It is usually encrypted with Apple’s FairPlay DRM technology. Each .ipa file is compressed with a binary for the ARM architecture and can only be installed on an iPhone, iPod Touch, or iPad.

In  Xcode 4.3, Apple has made it even easier to generate an IPA when compared to Xcode 4.2.  This tutorial will describe about the easiest way to generate an IPA in step by step.

I hope you already have an apple developer account & ad hoc distribution profile. If you don’t have please created it first and then continue.

Step 1: Click on the project name and select target->build Settings->code signing.

basic-5-2

Step 2. Select appropriate distributed provision Profile in the code signing identity.

Creating ipa using Xcode 08

Step 3:  Select iOS Device from the list of targets.

Creating ipa using Xcode 09

Step 4: Go to Product menu & Click on Archive.

Creating ipa using Xcode 10

Step 5: It takes some time to build your archive file depends upon your project file size. So please wait until it completes.

Step 6: After the archive is build successfully,  Open the Organiser  by using one of the following option

1)From Xcode, Go to window menu >> Click on Organizer.

2)Press Cmd + Shift + 2

Creating ipa using Xcode 02

Step 7: In the Organizer select the archive tab & select your latest build Archive from the list and Click on Distribute button.

Creating ipa using Xcode 14

Step 8: Select the Enterprise or  ad-hoc deployment option & Click on next button.

Creating ipa using Xcode 15

Step 9: Select Code Signing Identity and Click on Next button.

(Note:Code signing identity selected here  should be the same to the one which you used to build archive.)

Creating ipa using Xcode 16

Step 10: Finally, Select the location where you want to save an ipa.

Creating ipa using Xcode 13

That’s it.

 
2 Comments

Posted by on January 1, 2013 in iOS

 

Tags: , , , ,

How to display a Splash Screen in PhoneGap based IOS and Android application?

For displaying a splash screen image in phonegap based iOS application, just you need add the splashscreen image  with the name Default.png in the application directory as like in native application.

But if want to display a splash screen in Sencha touch &amp; Phonegap based Android application you need to add single line code and modify the loadurl method in the onCreate method of main activity.

Before doing modification you need to add the Splash screen image(splashscreen.png) in the drawable folder of application directory. After putting the image in drawable folder, add the  following line in your onCreate method of mainActivity file before super.loadUrl method.

super.setIntegerProperty(“splashscreen”, R.drawable.
splashscreen);

Then  modify the  loadURL method by adding the timeout parameter, which defines the length of time the splash screen should be displayed in milliseconds. 

super.loadUrl(“file:///android_asset/www/index.html”, 30000);

 That’s it. It will show the splashscreen image at the beginning of the application  for 30 seconds.

(NoteIf you get the white screen in between the splash screen and application home page, then increase the displaying time of splash screen.) 

After modification your onCreate method will look like this

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty(“splashscreen”, R.drawable.
splashscreen);
super.loadUrl(“file:///android_asset/www/index.html”, 30000);
}

 
2 Comments

Posted by on December 31, 2012 in PhoneGap, Sencha Touch

 

Tags: , , ,