Common method in Swift

1. Check for any field empty in NSDictionary

class func checkforEmptyValueinDictioanty(dic:NSDictionary)-> Bool{

for (keyVal, dataVal) in dic {

  if (dataVal.length()==0){

                println(\(keyVal): \(dataVal.length()))

                return false




        return true


2.Email validation

class func isValidEmail(testStr:String) -> Bool {

let fullNameArr = testStr.componentsSeparatedByString(“@”)

        var firstPart: String = fullNameArr[0]

        if let range = firstPart.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet()){


            return false


      let emailRegEx = “[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}”

 var emailTest = NSPredicate(format:“SELF MATCHES %@”, emailRegEx)

        let result = emailTest.evaluateWithObject(testStr)

        return result


3. Alert in Swift

class func commonAlert(title:String,msg:String,curView:UIViewController){

        var device : UIDevice = UIDevice.currentDevice();

        var systemVersion = device.systemVersion;

        var iosVerion : Float = (systemVersion as NSString).floatValue

        if(iosVerion >= 8.0) {


        var alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: “Ok”, style: UIAlertActionStyle.Default, handler: nil))

                  // return alert

            curView.presentViewController(alert, animated: true, completion: nil)


            let alert=UIAlertView(title: title, message: msg, delegate: self, cancelButtonTitle: “ok”)





4. NSUserDefaults in swift as common function

class func saveToUserDefault(value:AnyObject, key:String)


        NSUserDefaults.standardUserDefaults().setObject(value, forKey:key)




    class func userDefaultForKey(key:String) -> String


        return NSUserDefaults.standardUserDefaults().objectForKey(key) as NSString



    class func userDefaultForAny(key:String) -> AnyObject


        return NSUserDefaults.standardUserDefaults().objectForKey(key) as AnyObject!



    class func userdefaultForArray(key:String) -> Array<AnyObject>


        return NSUserDefaults.standardUserDefaults().objectForKey(key) as Array



    class func removeFromUserDefaultForKey(key:String)






5.Get screen height and width

let _screenWidth=UIScreen.mainScreen().bounds.size.width

let _screenHeight=UIScreen.mainScreen().bounds.size.height


Use different font text in a Label in swift

let secondLabel=UILabel(frame: CGRectMake(0, 16, _screenWidth2, 20))



        secondLabel.font=UIFont(name: “Arial”, size: 12)



        let attrSting=NSMutableAttributedString(string: “I agree to the Terms of Service and Privacy Policy.”)


        NSLog(“text length is %d”, attrSting.length)


        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica-bold”, size: 14), range: NSMakeRange(15, 16))


        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica”, size: 12), range: NSMakeRange(31,4 ))


        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica-bold”, size: 14), range: NSMakeRange(35, 15))



Use HexColor in Swift as a color

Add it in your class 

extension UIColor {

   convenience init(red: Int, green: Int, blue: Int) {

       assert(red >= 0 && red <= 255, “Invalid red component”)

       assert(green >= 0 && green <= 255, “Invalid green component”)

       assert(blue >= 0 && blue <= 255, “Invalid blue component”)

       self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)


   convenience init(netHex:Int) {

       self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)



Use it where you need…….

var color = UIColor(red: 0xFF, blue: 0xFF, green: 0xFF)

var color2 = UIColor(netHex:0xFFFFFF)

Json Parsing Using PhoneGap

Step 1. Call Js function From html page or from where you want like this

function onBodyLoad()
        document.addEventListener(“deviceready”, callJson, false);

Step 2.
Create a function of name callJson and call parsing Function from it in js file.

function callJson() {
    var webUrl = url;

Step 3.

function check(API) {
    var http_request = new XMLHttpRequest();
    alert(http_request);“GET”, API, false);
    var my_JSON_object = http_request.responseText;
    var data = JSON.parse(my_JSON_object);
    var html = ”;
        var _length=data.Regions.Region.length;    
        for(var i=0; i<_length;i++){
            var _resort=data.Regions.Region[i];
            var totalResorts=_resort.count;
            var _resionDic={
            html += ‘<li>  <a href=”#” ></a>’'</li>’;            
           for(var j=0; j<totalResorts;j++){
               var _resortDic={
        var arr=Resionlist[0];
        var m=0;

Best Of Luck.

Sencha Tutorial 1

In this series we will create the Sencha Touch 2 version of the Notes Application, an application that allows its users to take notes and store them on the device running the app. Along the way, we will dive into the following areas:

  • The building blocks of a Sencha Touch application.
  • How to implement navigation in an application with multiple views.
  • How to edit data using Sencha Touch form elements.
  • How to render information using lists views.
  • How Sencha Touch stores data with HTML5 local storage.

Note: An expanded version of this tutorial that covers creating a production build of the application is available in my Sencha Touch book.

In the first part of the series, we are going to define the features of the application, its look and feel, and we will start building its main screen.

The Features Of The Notes App

We want our app to give its users the following abilities:

  • Create notes.
  • Edit existing notes.
  • Delete notes.
  • Render a list of the notes currently saved on the device.
  • Persist notes on the device running the application, across browser sessions.

The Application’s User Interface

The main screen of the Notes App will render a list of the existing notes. We will name this View NotesListContainer. Here is its mockup, depicting the Sencha Touch Components we will use to build it:

As you can see, the NoteListContainer View is an Ext.Container Component that hosts a Toolbar Component and a List Component. We will treat the Ext.Lit as a separate View – the NotesList View.

A second screen, the NoteEditor View, will allow users to create, edit and delete notes. This view will look just like the following mockup:

The NoteEditor View is an Ext.form.Panel Component that contains a couple of Toolbars and the form elements needed to edit a note’s properties.

We also need a mechanism for our users to navigate to these screens. As each Sencha Touch Application gets a Viewport instance upon launch, we will use the Viewport to take care of rendering the NotesListContainer and NoteEditor Views, as well as manage the navigation between them:

The Viewport is ideal for this task. It extends from the Container Class, and it defaults to a full screen Card layout, which is what we need in the Notes App.

Organizing A Sencha Touch Application In Directories And Files

With the application features and user interface already defined, we can begin writing the source code. We will organize our source code in a directories tree like this:

We will place our files under the NotesApp directory, with the Application’s setup code in the app.js file.

We will also have an app directory, in which we will have the controller, model, profile, store, and view directories. The controllers, models, profiles, stores and views used in the Application will reside in these directories.

The index.html file will launch the app. In it, we will include the Sencha Touch framework, along with our application:

1 <!--<!DOCTYPE html>
2 <html>
3 <head>--> <!--Remove comments!-->
4     My Notes
5 <script type="text/javascript" src="../Lib/ST2/sencha-touch-debug.js"></script><script type="text/javascript"src="app.js"></script>
6 <!--</head>
7 <body>
8 </body>
9 </html>--> <!--Remove comments!-->

Note that we are keeping the framework files in the Lib/ST2 folder:

Creating a Sencha Touch Application Instance

Our first step in the app.js file will consist of creating an instance of the Sencha Touch Application Class. We are going to define an Application instance as follows:

1 Ext.application({
2     name: "NotesApp",
3     launch: function () {
5         console.log("App launch");
6     }
7 });

The application() method loads an Application instance after the page is ready, and it uses the supplied config object to configure the app. In our case, we are simply giving the app a name, and defining the launch() function.

One important role of the application() function is to trigger the load of any Models, Views, Controllers, Stores and Profiles the application depends on. This happens automatically when we define these dependencies using the models, views, controllers, stores and profiles config objects. We will see this feature in detail in this tutorial.

The launch() function is invoked as soon as the app loads its dependencies and instantiates its Controllers.

If we navigate to this page on the emulator, we should see something like this:

Extending Classes In Sencha Touch

We already know that the main screen of our application will render the list of notes currently cached on the device. To build this screen, we will use an instance of the Container Class, which will host a Toolbar and a List:

First, we will create the NotesListContainer.js file in the view directory:

In the NotesListContainer.js file, we will then define the NotesListContainer View like so:

1 Ext.define("NotesApp.view.NotesListContainer", {
2     extend: "Ext.Container",
3     config: {
4         items: [{
5             xtype: "toolbar",
6             docked: "top",
7             title: "My Notes",
8             items: [{
9                 xtype: "spacer"
10             }, {
11                 xtype: "button",
12                 text: "New",
13                 ui: "action",
14                 id:"new-note-btn"
15             }]
16         }]
17     }
18 });

Here we are using Ext.define() to define an extension to the Ext.Container class. We have added a Toolbar instance to this view, docked to the top. The Toolbar will in turn contain one Button, the New button, which will allow our users to activate the NoteEditor View and create a new note.

Pay attention to how we included a Spacer Component before the button. This will place the New button on the right end of the Toolbar. Also, how the ui=”action” config allows us to give the button a distinctive look, indicating that it represents the default button on the view.

Specifying Application Dependencies In Sencha Touch

With the NotesListContainer Class defined, it is time to make the Application aware of it. Back in the app.js file, we are going to add the views config to the application() function:

1 Ext.application({
2     name: "NotesApp",
3     views: ["NotesListContainer"],
5     launch: function () {
7         var notesListContainer = Ext.create("NotesApp.view.NotesListContainer");
8         Ext.Viewport.add(notesListContainer);
9     }
10 });

We inform the Application that it has a dependency on the NoteListContainer View by using the views config:

1 views: ["NotesListContainer"]

The Application Class expects its models, views, controllers, stores and profiles to exist in the app/model, app/view, app/controller, app/store, and app/profile directories. With this convention, we can define models, views, controllers, stores and profiles using the last part of their names, as we do here. If we use a different directory structure, we will need to refer to them using their fully qualified names.

Time to check out how the View looks. On the emulator, you should see something similar to this:

Very nice, right? Let’s move on to the Controller. We need a Controller Class to be in charge of handling user input, modifying the models, and governing the transitions between views.

Creating Sencha Touch Controllers

Let’s define a very simple Notes Controller Class. We will place this Class in the Notes.js file, which we will add to the controller directory:

And this is the Controller’s definition:

1 Ext.define("NotesApp.controller.Notes", {
2     extend: "",
3     launch: function () {
4         this.callParent();
5         console.log("launch");
6     },
7     init: function () {
8         this.callParent();
9         console.log("init");
10     }
11 });

Controllers contain a couple of functions, init() and launch(), that run at different moments during the Application’s startup process. The init() function is invoked by the framework before the Application’s launch() function. The Controller’s launch() function is invoked after the Application’s launch() function runs.

We will make the Application aware of the Notes Controller Class by adding this Controller to the app’s controllers config:

1 Ext.application({
2     name: "NotesApp",
3     controllers: ["Notes"],
4     views: ["NotesListContainer"],
6     launch: function () {
8         var notesListContainer = Ext.create("NotesApp.view.NotesListContainer");
9         Ext.Viewport.add(notesListContainer);
10     }
11 });

As we already know, having the Notes Controller Class listed in the controllers config will cause the Application to automatically instantiate and keep a reference to this Controller.

How To Handle View Events In a Sencha Touch Controller

At this point we have our Controller set up, and we are ready to start adding features to it. The first thing the Notes Controller needs to do is handle taps on the New button. We can accomplish this by making the following modification to the Controller’s definition:

1 Ext.define("NotesApp.controller.Notes", {
2     extend: "",
3     config: {
4         refs: {
5             newNoteBtn: "#new-note-btn"
6         },
7         control: {
8             newNoteBtn: {
9                 tap: "onNewNote"
10             }
11         }
12     },
13     onNewNote: function () {
14         console.log("onNewNote");
15     }
17     // init and launch functions omitted.
18 });

Notice the change? Exactly – the refs and control configurations. They are the foundation of the mechanism by which a Controller acquires references to the Components in the app, and defines event handlers for them.

Refs give the Controller the ability to find Components in the app. They use the ComponentQuery Class, which retrieves components using a CSS selector-like syntax. I will not go into the details of ComponentQuery in this article, but I highly recommend that you take some time to study it.

In the Notes Controller, we use the newNoteBtn ref to create a reference to the Component whose id is #new-note-btn. This is the New button.

1 refs: {
2     newNoteBtn: "#new-note-btn"
3 }

Based on this ref, the framework generates a getter function that we can use to work with the New button reference if we need to. Ref-derived getter functions are named following a simple format, consisting of the word get and the capitalized name of the ref in question. In our case, the name of the function will be getNewNoteBtn().

Refs also give us the ability to instantiate the components they reference if such components do not already exist. Although we are not taking this approach in our app, I recommend that you study these features. They are important, especially if you will be building large applications where you cannot afford or do not need to instantiate all the application’s components upon application launch.

The control config allows us to define event handlers for any of the Application’s Components. We can use refs or ComponentQuery selectors to define event handlers within control. In the Notes Controller, we are using the newNoteBtn ref to define a tap handler for the New button:

1 control: {
2     newNoteBtn: {
3         tap: "onNewNote"
4     }
5 }

Obviously, we also need to define the handler function, which we do further down in the Controller’s source:

1 onNewNote: function () {
2     console.log("onNewNote");
3 }

The onNewNote() function is simply writing a message to the console, but we will soon add to it the code that will open the NoteEditor View.

Let’s take a moment to check the application on the emulator. In particular, what happens when we tap the New button. If a tap occurs, the console output should display the message we just added in the onNewNote() handler:

One important takeaway from this tutorial is that when you need your Controller to handle a particular event on a Component, you can follow these steps:

  1. Create a ref for the Component.
  2. Create an entry for the ref in the Controller’s control config.
  3. Use the entry in the control config to specify the handler for the events in which you are interested.

How to install phone gap .

Getting Started with iOS

This guide describes how to set up your development environment for Apache Cordova and run a sample Apache Cordova application.


  • Xcode 4.5+
  • Xcode Command Line Tools
  • Intel-based computer with Mac OS X Lion or greater (10.7+)
  • Necessary for installing on device:
    • Apple iOS device (iPhone, iPad, iPod Touch)
    • iOS developer certificate

Install the iOS SDK and Apache Cordova

  • Install Xcode from the Mac App Store or Apple Developer Downloads
  • Install the Xcode Command Line Tools (Xcode Preferences -> Downloads -> Components -> Command Line Tools -> Install).
  • Download the latest release of [Apache PhoneGap
    • extract its contents
    • Apache Cordova iOS is found under lib/ios

Install CordovaLib

  1. Download the Cordova source
  2. Extract the source to their final permanent location on your hard drive (for example, to ~/Documents/Cordova-2.X.X)
  3. There is no step 3

Create a New Project

  • Launch
  • Drag the bin folder (located in the permanent folder location of Cordova, from the “Install CordovaLib” section above) to the icon in your Dock, it should launch a new Terminal window
  • Type in ./create <project_folder_path> <package_name> <project_name> then press “Enter”

    <project_folder_path> is the path to your new Cordova iOS project (it must be empty if it exists)
    <package_name> is the package name, following reverse-domain style convention
    <project_name> is the project name

  • Locate your new project folder that you just created

  • Launch the .xcodeproj file in the folder

Note: Starting with Cordova 2.2, the project will have a copy of CordovaLib within it instead of having a dependency on the copy of CordovaLib from your Cordova installation.

If you would like your project to depend directly on your Cordova installation’s version of CordovaLib, you can use: ./create --shared, or change the project reference after creation using: ./update_cordova_subproject path/to/you/project.

Deploy to Simulator

  • Change the Target in the Scheme drop-down menu on the toolbar to “HelloWorld” (your project name)
  • Change the Active SDK in the Scheme drop-down menu on the toolbar to iOS [version] Simulator

  • Select the Run button in your project window’s toolbar

Deploy to Device

  • Open HelloWorld-Info.plist, under the Resources group
  • Change BundleIdentifier to the identifier provided by Apple or your own bundle identifier
    • If you have a developer license, you can run the Assistant to register your app
  • Change the Target in the Scheme drop-down menu on the toolbar to “HelloWorld” (your project name)
  • Change the Active SDK in the Scheme drop-down menu on the toolbar to [Your Device Name]

    • You will need to have your device connected via USB


  • Select the Run button in your project window’s toolbar


  • You should see the screen below, with a pulsating green “device is ready” message

Problems in Xcode

If you have compilation problems related to missing headers, the build products should build into the same build directory. You may need to set the preference “Xcode Preferences -> Locations -> Derived Data -> Advanced…” to “Unique”. This is the default setting for Xcode on a fresh new install, if you upgraded from older versions of Xcode, you might have a legacy preference in there that you need to update.

Build Your App

You now have an Xcode project setup and you can build and run on the Simulator and device. It is important to understand that you do not need to use Xcode to write your web application. You can use your favourite text editor and simply rebuild your project using Xcode, or the command-line tools in your project folder (under the cordova sub-folder) Xcode will automatically detect the files that are changed in www.

Problems in the Command Line Tools

If you see this error: “Error: No developer directory found at /Developer. Run /usr/bin/xcode-select to update the developer directory path.” Run this to set your Developer folder:

    sudo /usr/bin/xcode-select -switch /Applications/