Tuesday, December 23, 2014

Swift: A new programming language for iOS and OS X.

WelCome TO Swift

Introduction to Swift

Swift is an innovative new programming language for Cocoa and Cocoa Touch. Writing code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast. Swift is ready for your next iOS and OS X project — or for addition into your current app — because Swift code works side-by-side with Objective-C.




With the release of Xcode 6.1 and iOS 8, Swift 1.1 is final, and you can build and submit your iOS apps written with Swift to the App Store



The Basics 

Swift does away with the standard of declaring variables by starting with their type names, and instead opts to use a Javascript-like ‘var’ keyword to define any variable.
    So for instance in Objective-C where you have this:


NSString *myString = @"This is my string.";
    You now have this:

var myString = "This is my string."

Meanwhile constants are expressed with the ‘let’ keyword


let kSomeConstant = 40
In this case kSomeConstant is implicitly defined as an integer. If you want to be more specific you can specify which type it is like so:


let kSomeConstant: Int = 40

With both arrays and dictionaries, they are described using brackets [ ]


var colorsArray = ["Blue", "Red", "Green", "Yellow"]
var colorsDictionary = ["PrimaryColor":"Green", "SecondaryColor":"Red"]



There’s a lot more to go over, but I think these basics are important to get a start going on to the tutorial. So with that, let’s move on to Hello World.


EX.
Hello World
First, we’re going to write the simplest app imaginable to get started, Hello World. Our app will only do one thing: print “Hello World” to the console.
Set up an Xcode project using the single-view application template, and make sure you opt for Swift as the language.



You should now find an AppDelegate.swift file in the project hierarchy
IN didFinishLaunchingWithOptions write below code.

println("Hello World")

Now press run and you should see a blank app boot up, and the words “Hello World” print to the console.
Note that this will not show up in the iPhone simulator. Look at the bottom of your Xcode window and you’ll see a console that says ‘Hello World!’.



Adding a Table View

In this section, we’re going to actually put some stuff on the screen, yay!
Open up your Main.storyboard file in Xcode and lets drag in a “Table View” object from the Object Library (don’t use a table view controller.) Position this fullscreen in your app window and make sure it lines up with the edges.

Then resize the height by dragging down the top edge and giving a little bit of space (this gives room for the status bar at the top of the phone.) If you run the app at this point, you should see an empty table view in the simulator.




NOW, in ViewController.swift add Data Source & Delegate :

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

& then modify our View Controller class by adding these two functions for UITableView methods

func tableView(tableView: UITableView, numberOfRowsInSection section:    Int) -> Int {
   return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
   let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")

   cell.textLabel?.text = "Row #\(indexPath.row)"
   cell.detailTextLabel?.text = "Subtitle #\(indexPath.row)"

   return cell
}

The first method is asking for the number of rows in our section, in this simple tutorial we just hard-code 10, but normally it would be the length of an array controller. This example is intentionally simple.

The second method is where the magic happens. Here we create a new instance of a UITableViewCell called cell, using the Subtitle cell style.
Then, we assign the text value of this cell to the string “Row #\(indexPath.row)”
In Swift, this is how variables are embedded within a string. What we’re doing is retrieving the value of indexPath.row by inserting \(indexPath.row) in to our string, and dynamically replacing it with the row number of the cell. This allows results such as “Row #1″, “Row #2″, etc.
The detail text label is only available in the Subtitle cell class, which we are using here. We set it similarly to “Subtitle #1″, “Subtitle #2″, and so on.

So, Complete Code is Given Below.
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "MyTestCell")
        
        cell?.textLabel?.text = "Row #\(indexPath.row)"
        cell?.detailTextLabel?.text = "Subtitle #\(indexPath.row)"
        
        return cell!
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

//Output --------------->>>



Go ahead and run your app and you’ll now see an amazing list of cells with titles and subtitles indicating their row numbers. This is one of the most common ways to display data in iOS, and will be sure to serve you well.

For More info about Swift ,  Click Here




iOS Quick Tip: 5 Tips to Increase App Performance

In this quick tip,  five tips to improve application performance.

1. Caching


2. Do Not Block the Main Thread


3. Lazy Loading


4. Measure Performance


5. Stress Testing



1. Caching

If an iOS application fetches a remote resource, it is important that it doesn't fetch that same resources every time it needs to access it. If you plan to develop a Twitter client for iOS, for example, then the client shouldn't be downloading the same avatar every time it needs to display it. Caching the avatar will significantly improve application performance.
What is caching? The basic idea of caching is simple. When the application fetches a remote resource for the first time, it stores a copy of that resource on disk for later use. If that same resource is needed later, the application can load it from disk instead of fetching it remotely. The added benefit is that the resource is also available when the device is not connected to the web. The complex aspect of caching is how to store the resource, when to store it, and, most importantly, when to refresh it.
Olivier Poitrey has developed a small library named SDWebImage that is aimed at caching images. It provides a category on UIImageView much like AFNetworkingdoes. The key difference is that SDWebImage caches the images it downloads. Images are downloaded in the background and each images is decompressed, resulting in faster load times. The library leverages Grand Central Dispatch to keep the main thread responsive. If your application works with remote images, then you should take a look at this gem.


2. Do Not Block the Main Thread

One of the most important lessons to learn when developing for the iOS platform is to never block the main thread. If you block the main thread with a long running operation, such as downloading images or other resources, your application will become unresponsive as long as the operation isn't completed. Make it a habit to move long running tasks to a background thread. Even if you only need a handful of bytes, if the device's connection to the web is slow, the operation will still block the main thread.
Writing safe multithreaded code has become a lot easier with the introduction of Grand Central Dispatch. Take a look at the following code snippets. The first snippet downloads data on the main thread, while the second snippet leverages Grand Central Dispatch to perform the same task on a background queue.

NSData *data = [NSData dataWithContentsOfURL:URL];
UIImage *image = [UIImage imageWithData:data];
[imageView setImage:image];

dispatch_queue_t queue = dispatch_queue_create("downloadAsset",NULL);

dispatch_async(queue, ^{
    NSData *data = [NSData dataWithContentsOfURL:URL];

    dispatch_async(dispatch_get_main_queue(), ^{
        UIImage *image = [UIImage imageWithData:data];
        [imageView setImage:image];
    });
});

3. Lazy Loading

Being lazy isn't always bad especially if you are a programmer. Lazy loading is a well known concept in software development. It simply means that you postpone the instantiation of an object until you need the object. This is advantageous for several reasons. Depending on the object and the cost for instantiation, it can dramatically improve application performance and memory usage. Lazy loading objects isn't a difficult concept. The simplest implementation of this pattern is overriding the getter of a property as shown below.

- (MyClass *)myObject {
    if (!_myObject) {
        _myObject = [[MyClass alloc] init];
    }

    return _myObject;
}

The lazy loading pattern can be applied in many areas of software development. For example, if part of your application's user interface is not shown by default, it may be advantageous to postpone its instantiation until that part is about to be shown.
Table and collection views use a combination of caching and lazy loading to optimize performance. If the next cell or item is about to be displayed on screen, the table or collection view looks for a cell or item it can reuse (caching). Only if no reusable cell or item is available will the table or collection view (or its data source) instantiate a new cell or item (lazy loading).


4. Measure Performance

If you notice that your application is slow at times and you want to find out what is causing it, then you may need to profile your application with a tool such as Instruments. Colin Ruffenach wrote a nice tutorial about time profiling with Instruments on Mobiletuts+.
If Instruments doesn't give you a clear answer, you may be interested inMGBenchmark, a benchmarking library developed and maintained by Mattes Groeger. This compact library lets you measure how fast your code executes and it helps you to track down the bottlenecks in your code base. It actually complements Instruments quite well so you shouldn't use one or the other. Mattes Groeger's library comes with an extensive feature set and is remarkably powerful. I highly recommend it as an alternative or complement to Instruments.


5. Stress Testing

If you're developing an application that works with lots of data, then it is important to test it with...well...lots of data! During the development of an application, it isn't always easy or possible to imagine how your users are going to use your application, but it is good to put it through its paces before releasing it. Your application may perform admirably during development and perform terribly in situations where it is flooded with data. You probably won't be able to predict, let alone test, all the circumstances in which your application will be used, but you can try to mimic common situations by creating data sets to test with.
I often create a small script or class that populates the application with test data to measure how well it performs with a lot of data. Ideally, you want to populate the application with more test data than an average user will have - to the extent that you can predict this during development. When I was developing Pixelsync, an iPad application that interfaces with Aperture and iPhoto, I created an Aperture library with close to 500,000 images. If Pixelsync performed well with a photo library of that size, I could be fairly confident that the average user wouldn't run into performance issues.
If you really are a lazy developer or you just don't have enough time, then you can also be more creative by building a robot to do the job for you.



Conclusion


Application performance remains an essential aspect of software development despite the fact that the new generation of devices are much more powerful and capable. Blocking the main thread, for example, will always result in a bad user experience no matter how capable the device is.

Monday, December 22, 2014

WatchKit -Get your iPhone app ready for Apple Watch.

WatchKit

What is WatchKit?


You may think that WatchKit is a framework that contains everything you need to create an Apple Watch application, but that is only part of the story. The story is a bit more complex, because an Apple Watch application isn't what you may think it is.
WatchKit is an integral part of the Apple Watch experience for third-party applications. It contains the classes for creating Apple Watch applications and it ensures that an Apple Watch application can talk to its corresponding WatchKit extension.

Architecture

One of the most important concepts to grasp about Apple Watch applications is that an Apple Watch application requires an iPhone to do its work. To understand this concept, we need to take a closer look at the architecture of an Apple Watch application.

A third-party Apple Watch application can only do its work if the user's Apple Watch is paired with the their iPhone. The Apple Watch and the iPhone talk to each other using Bluetooth and the WatchKit framework. The following diagram summarizes this architecture.


What is an Apple Watch application?

You may be wondering what an Apple Watch application is and how you can create one. Strictly speaking, an Apple Watch application is the component that runs on Apple Watch. An Apple Watch application presents the user interface and intercepts touch events.
This means that an Apple Watch application is unusable without the paired device on which the corresponding WatchKit extension runs. The Apple Watch application and WatchKit extension are part of the iOS application the user installs on their iPhone.


iPhone Required

As I mentioned earlier, it is key to understand that third-party Apple Watch applications require an iPhone and are unusable without a paired iPhone on which the corresponding WatchKit extension lives.
The good news is that the WatchKit framework takes care of the nitty-gritty details. It automatically pairs iPhone and Apple Watch, and handles the communication between the Apple Watch application and the WatchKit extension. Communication between iPhone and Apple Watch is handled by Bluetooth.


WatchKit Extension

When the user launches an Apple Watch application from the home screen, the paired iPhone launches the WatchKit extension for that application. Any user interaction is forwarded to the WatchKit extension and it is the latter's responsibility to decide how the Apple Watch application should respond to user interaction.

Apple Watch Application

Only the storyboard and static resources of the Apple Watch application are installed on the Apple Watch. As I mentioned a moment ago, none of the business logic is handled on the Apple Watch.
While this may seem like a major limitation, it certainly has advantages. For example, the Apple Watch application has, through the WatchKit extension, access to the data of the corresponding iOS application. The Apple Watch application can also take advantage of the device capabilities of the iPhone, such as location monitoring and network connectivity.

Installation

Installing an Apple Watch application is trivial. Whenever the user installs an iOS application that supports Apple Watch, the user is asked if it wishes to install the corresponding Apple Watch application. It's that simple.



Glances and Notifications

During Apple's keynote in september, you may have heard about glances and notifications. An Apple Watch application can present itself to the user in three ways.

Application

The most obvious representation of an Apple Watch application is when the user launches the application form the Apple Watch home screen. This launches the user interface of the Apple Watch application and lets the user interact with it.


Glances

In terms of functionality, a glance is similar to a today extension on iOS. It shows the user relevant information about the Apple Watch extension. The main difference with a today extension is that glances are read-only. Also note that it's perfectly possible to create an Apple Watch application without support for glances.


Notifications

In addition to the default user interface of local and remote notifications, it's possible for Apple Watch applications to include a custom user interface for local and remote notifications. As with glances, this is optional for Apple Watch applications.



Navigation & Interaction

The Apple Watch has a tiny screen compared to the iPhone 6 and 6 Plus. The result is that navigation and user interaction is different and more limited on Apple Watch.


Navigation

The WatchKit framework currently includes two types of navigation, hierarchical and page-based navigation. Hierarchical navigation is very similar to howUINavigationController handles navigation on iOS while page-based navigation is similar to the way UIPageViewController lets the user scroll between pages of content.

User Interaction

The more you learn about and play with WatchKit, the more you notice how different it is from iOS and the paradigms defined by the iOS ecosystem. User interaction, for example, is quite different. The WatchKit framework doesn't allow for complex gesture detection and it's also not possible to use custom gesture recognizers.
Understanding user interaction on Apple Watch is pretty straightforward. There are five types of user interaction:
  • Taps: The user taps the screen to select a table row.
  • Vertical Swipe: The user scrolls the contents of a table.
  • Horizontal Swipe: The user navigates between pages in a page-based navigation.
  • Left Edge Swipe: As on iOS, it is possible to navigate back to the previous screen by swiping from the left edge of the screen to the right.
  • Force Touch: Unique to Apple Watch, the user can press or force touch the screen to display a contextual menu. The display of Apple Watch not only detects touch, but it also detects force.


Digital Crown

In addition to manipulating the content on the screen, the user can also interact with the Apple Watch using its Digital Crown. With regards to third-party applications, the Digital Crown can only be used to scroll through content.


Limitations

There are a number of limitations when it comes to developing Apple Watch applications. We already learned that user interaction and navigation isn't as powerful on Apple Watch as it is on iOS and there are a few more restrictions you need to be aware of.
Animations, for example, aren't as powerful or easy to implement on Apple Watch. Animations are created by displaying a sequence of images to the user. Dynamically adding and removing views is also something that isn't possible on Apple Watch. In fact, views are non-existent on Apple Watch and the same is true for auto layout.
Instead, the WatchKit framework exposes the WKInterfaceController class, which manages one screen of content. The controls used on Apple Watch are also different than those used on iOS. There are many similarities, but it will require some getting used to.
These limitations shouldn't be a surprise. Apple Watch is different from the iOS ecosystem and it is understandable that the patterns and paradigms for each are different.


Resources

If you want to learn more about WatchKit, then you have a number of options. I recommend you first watch Apple's introductory video. If you want to dive deeper into the WatchKit framework, then the WatchKit Programming Guide is your next stop. Designers may be interested in browsing the Apple Watch Human Interface Guidelines.

If you're eager to get started, then I encourage you to download Xcode 6.2 and get your hands dirty with WatchKit. Xcode's simulator supports Apple Watch so there's nothing stopping you from creating your first Apple Watch application today.

Friday, December 19, 2014

IOS Sqlite Database-Insert, Update & Delete

// First of all add project > Build Phase > Link Binary with Library > add - libsqlite.dylib

#import <sqlite3.h>  //import in Appdelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    //FOR DB
    NSString *databasePath;
    sqlite3 *myDatabase;
}
@property (strong, nonatomic) UIWindow *window;
-(void)dbcheck;


//-- for DB--
@property (strong, nonatomic) NSString *databasePath;


// in .m
#import "DBConnection.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //DB check--
    [self dbcheck];
 }

-(void) dbcheck
{
    // Get the documents directory
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsDir = dirPaths[0];
    //    NSString *path_Folder_Document = [[NSString alloc] initWithString: docsDir];
    
    // Build the path to the database file
    self.databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:@"database.sqlite"]];     //set your Database name
    NSLog(@"self.databasePath =%@",self.databasePath);
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:self.databasePath];
    NSLog(@"Database file database.sqlite already exist =%hhd",fileExists);
    
    if (!fileExists)
    {
        NSLog(@"New database file created..");
        const char *dbpath = [self.databasePath UTF8String];
        if (sqlite3_open(dbpath, &myDatabase) == SQLITE_OK)
        {
            char *errMsg;
            
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS DD(todo_key_id integer primary key not null, todo_notes text null,todo_notes_l text null)";
            
            if (sqlite3_exec(myDatabase, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                NSLog(@"Failed to create table DD %s",errMsg);
            }
            else
            {
                NSLog(@"Table DD..done");
            }
            
            sqlite3_close(myDatabase);
        }
        else
        {
            NSLog(@"Failed to open/create database");
        }
    }
}

// in ViewController Import Library files & use it.

#pragma mark - fetchDatabase Method

-(void)fetchDatabase
{
    // fetch (Get) Database from Server
    ArrTodoList=[[DBConnection fetchResults:[NSString stringWithFormat:@"SELECT * FROM DD"]] mutableCopy];
    NSLog(@"Refresh Data in ArrTodoList -> %@",ArrTodoList);
}



 //INSERT DATA INTO DATABASE
        NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO DD(todo_notes,todo_notes_l) VALUES (\"%@\",\"%@\")",string2,stringL];
        NSLog(@"insertSQL =%@",insertSQL);
        
        if ([DBConnection executeQuery:insertSQL])
        {
            NSLog(@"Data is inserted executed");
        };



// Delete Selected Data from Database
            NSString * DeleteQuery= [NSString stringWithFormat:@"DELETE from DD WHERE todo_notes = '%@' ",[NSString stringWithFormat:@"%@",[ArrSelected objectAtIndex:i]]];
            
            NSLog(@"DeleteQuery =%@",DeleteQuery);
            
            if ([DBConnection executeQuery:DeleteQuery])
            {
                NSLog(@">>> Delete DeleteQuery.................");
            };



 //Update Arr_destination from DB
    NSString *SQL_Update = [NSString stringWithFormat:@"UPDATE DD SET todo_notes = \"%@\" , todo_notes_l = \"%@\" WHERE todo_key_id = \"%@\"" ,[Arr_source valueForKey:@"todo_notes"],[Arr_source valueForKey:@"todo_notes_l"],[Arr_destination valueForKey:@"todo_key_id"]];
    
    if([DBConnection executeQuery:SQL_Update])
    {
        NSLog(@">>> Update SQL_Update.....");

    };

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Library files for Sqlite Database is Given Below.
1.DBConnection.h
2.DBConnection.m

1.DBConnection.h
#import <Foundation/Foundation.h>
#import <sqlite3.h>

// database name demo.sqlite

#define DB_NAME @"database.sqlite"// <<<-Set your database name here

@interface DBConnection : NSObject 
{
    @private sqlite3 *myDatabase;
}

@property (nonatomic,assign,readwrite) sqlite3 *database;

+ (DBConnection *) sharedConnection;
+ (BOOL) executeQuery:(NSString *)query;
+ (NSMutableArray *) fetchResults:(NSString *)query;
+ (int) rowCountForTable:(NSString *)table where:(NSString *)where;
+ (void) errorMessage:(NSString *)msg;
+ (void) closeConnection;

- (id)initConnection;
- (void)close;

@end


// query

// 1) CREATE TABLE IF NOT EXISTS NTN (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,name TEXT)
// 2) INSERT INTO NTN (name) VALUES ('nitin')
// 3) DROP TABLE NTN
// 4) DELETE FROM NTN
// 5) DELETE FROM SQLITE_SEQUENCE WHERE name='NTN'
// 6) SELECT * FROM NTN
// 7) SELECT * FROM NTN ORDER BY id DESC
// 8) SELECT * FROM NTN GROUP BY name
// 9) SELECT * FROM NTN ORDER BY name DESC

2.DBConnection.m


#import "DBConnection.h"
#include <sys/xattr.h>

//static sqlite3_stmt *statement = nil;

#define DB_NAME @"database.sqlite"//@"Conferencedata////NSLog"

@interface DBConnection (Private)
- (void) createEditableCopyOfDatabaseIfNeeded;
- (BOOL) addSkipBackupAttributeToItemAtURL:(NSURL *)URL;
- (void) initializeDatabase;
@end

@implementation DBConnection
static DBConnection *conn = NULL;

@synthesize database = g_database;

+ (DBConnection *) sharedConnection {
if (!conn) {
conn = [[DBConnection alloc] initConnection];
}
return conn;
}

#pragma mark - Static Methods

+(BOOL) executeQuery:(NSString *)query{
    BOOL isExecuted = NO;
    
    sqlite3 *database = [DBConnection sharedConnection].database;
    sqlite3_stmt *statement = nil;
    const char *sql = [query UTF8String];
    if (sqlite3_prepare_v2(database, sql, -1, &statement , NULL) != SQLITE_OK)
    {
        //NSLog(@"Error: failed to prepare agenda query statement with message '%s'.", sqlite3_errmsg(database));
        //NSString *errorMsg = [NSString stringWithFormat:@"Failed to prepare query statement - '%s'.", sqlite3_errmsg(database)];
        //[DBConnection errorMessage:errorMsg];
        //NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
        return isExecuted;
    }
    
    // Execute the query.
if(SQLITE_DONE == sqlite3_step(statement)) {
        isExecuted = YES;
    }
    
// finlize the statement.
sqlite3_finalize(statement);
    statement = nil;
    
    return isExecuted;
}
+(NSMutableArray *) fetchResults:(NSString *)query{
    NSMutableArray *results = [NSMutableArray arrayWithCapacity:0];
    sqlite3 *database = [DBConnection sharedConnection].database;
    sqlite3_stmt *statement = nil;
    
    const char *sql = [query UTF8String];
    if (sqlite3_prepare_v2(database, sql, -1, &statement , NULL) != SQLITE_OK) {
        //NSLog(@"Error: failed to prepare fetch results statement with message '%s'.", sqlite3_errmsg(database));
        NSString *errorMsg = [NSString stringWithFormat:@"Failed to prepare query statement - '%s'.", sqlite3_errmsg(database)];
        [DBConnection errorMessage:errorMsg];
        //NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
        return results;
    }
    
    while (sqlite3_step(statement) == SQLITE_ROW) {
        
        id value = nil;
        NSMutableDictionary *rowDict = [NSMutableDictionary dictionaryWithCapacity:0];
        for (int i = 0 ; i < sqlite3_column_count(statement) ; i++) {
            
            /*
             if (strcasecmp(sqlite3_column_decltype(statement,i),"Boolean") == 0) {
             value = [NSNumber numberWithBool:(BOOL)sqlite3_column_int(statement,i)];
             } else */
            
            if (sqlite3_column_type(statement,i) == SQLITE_INTEGER) {
                value = [NSNumber numberWithInt:(int)sqlite3_column_int(statement,i)];
            } else if (sqlite3_column_type(statement,i) == SQLITE_FLOAT) {
                value = [NSNumber numberWithFloat:(float)sqlite3_column_double(statement,i)];
            } else {
                
                if (sqlite3_column_text(statement,i) != nil) {
                    value = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,i)];
                } else {
                    value = @"";
                }
            }
            
            if (value) {
                [rowDict setObject:value forKey:[NSString stringWithUTF8String:sqlite3_column_name(statement,i)]];
            }
        }
        
        [results addObject:rowDict];
        ////NSLog(@"rowDict -- %@", rowDict);
    }
    
    sqlite3_finalize(statement);
    statement = nil;
    
    return results;
}
+(int) rowCountForTable:(NSString *)table where:(NSString *)where{
    int tableCount = 0;
NSString *query = @"";
    
    if (where != nil && ![where isEqualToString:@""]) {
        query = [NSString stringWithFormat:@"SELECT COUNT(*) FROM %@ WHERE %@",
                 table,where];
    } else {
        [NSString stringWithFormat:@"SELECT COUNT(*) FROM %@",
         table];
    }    
    
sqlite3_stmt *statement = nil;
    
    sqlite3 *database = [DBConnection sharedConnection].database;
    const char *sql = [query UTF8String];
    if (sqlite3_prepare_v2(database, sql, -1, &statement , NULL) != SQLITE_OK) {
        return 0;
    }
    
if (sqlite3_step(statement) == SQLITE_ROW) {
        tableCount = sqlite3_column_int(statement,0);
    }
    
sqlite3_finalize(statement);
return tableCount;
}
+(void) errorMessage:(NSString *)msg{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}
+(void) closeConnection{
    sqlite3 *database = [DBConnection sharedConnection].database;
    if (sqlite3_close(database) != SQLITE_OK)
    {
        NSLog(@"any problem in db..to close connection");
        //NSAssert1(0, @"Error: failed to close database with message '%s'.", sqlite3_errmsg(g_database));
//        NSString *errorMsg = [NSString stringWithFormat:@"Failed to open database with message - '%s'.", sqlite3_errmsg(database)];
//        [DBConnection errorMessage:errorMsg];
    }
}
-(id) initConnection {
    self = [super init];
    
if (self) {
//database = g_database;
if (g_database == nil) {
// The application ships with a default database in its bundle. If anything in the application
// bundle is altered, the code sign will fail. We want the database to be editable by users, 
// so we need to create a copy of it in the application's Documents directory.     
[self createEditableCopyOfDatabaseIfNeeded];
// Call internal method to initialize database connection
[self initializeDatabase];
}
}
return self;
}

#pragma mark - save db

-(void)createEditableCopyOfDatabaseIfNeeded {
    // First, test for existence.
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
//    NSString *documentsDirectory = [paths objectAtIndex:0];
//    NSString *dbDirectory = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]]];
    
    AppDelegate *del = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    
    NSString *path=[del.databasePath copy];
//  const char *dbpath = [path UTF8String];
    
    
    
    if (![fileManager fileExistsAtPath:path])
    {
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
        [self addSkipBackupAttributeToItemAtURL:[[NSURL alloc] initFileURLWithPath:path isDirectory:YES] ];
    }
    NSString *writableDBPath = [path stringByAppendingPathComponent:DB_NAME];
    success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DB_NAME];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
//    if (!success) {
//        //NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
//        
//        NSString *errorMsg = [NSString stringWithFormat:@"Failed to create writable database file with message - %@.", [error localizedDescription]];
//        [DBConnection errorMessage:errorMsg];
//    }
}
-(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL{
    const char* filePath = [[URL path] fileSystemRepresentation];
    
    const char* attrName = "com.apple.MobileBackup";
    u_int8_t attrValue = 1;
    
    int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
    return result == 0;
}
#pragma mark - Open the database connection and retrieve minimal information for all objects.

-(void)initializeDatabase
{
    // Get the documents directory
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsDir = dirPaths[0];
    
    NSString *path = [docsDir stringByAppendingPathComponent:DB_NAME];
    //NSLog(@"path = %@ ",path);
////NSLog(@"SQLite Root: %s", [path UTF8String]);
    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([path UTF8String], &g_database) != SQLITE_OK) {
        // Even though the open failed, call close to properly clean up resources.
        sqlite3_close(g_database);
g_database = nil;
        //NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(g_database));
        NSString *errorMsg = [NSString stringWithFormat:@"Failed to open database with message - '%s'.", sqlite3_errmsg(g_database)];
        [DBConnection errorMessage:errorMsg];
    }
}
-(void)close {
if (g_database) {
// Close the database.
if (sqlite3_close(g_database) != SQLITE_OK) {
//NSAssert1(0, @"Error: failed to close database with message '%s'.", sqlite3_errmsg(g_database));
            NSString *errorMsg = [NSString stringWithFormat:@"Failed to open database with message - '%s'.", sqlite3_errmsg(g_database)];
            [DBConnection errorMessage:errorMsg];
}
g_database = nil;
}
}

@end

Steps to create new app in developer account & Steps to create new app in iTunes account

#Steps to create new app in developer account
  1. Login with credentials
  2. Create App id for the app if old version of that app is not available 
  3. Enable Push notification for app id.
  4. Add deices' UDID of client if given
  5. Create profiles (developer & distribution according to requirement).



#Steps to create new app in iTunes account
  • 1. Login with credentials
  • 2. Add new app if there is a new app.
  • 3. For Old app
    •  > Add new version.
    • > Make distribution profile (from developer acc.) with make sure that push notification is enable for that profile.
    • > Replace new screen shots with old one.
    • > Change demo account information to qa@grupio.com/test if not changed.
    • > Change key words if mention to change.
  • 4. Upload binary.

Arm 64 support in IOS APP for competible to IOS8

// —————————— Arm 64 support————————————  //

    
Architecture : $(ARCHS_STANDARD_INCLUDING_64_BIT)
Valid Architecture:  arm64,armv7,armv7s

>>.Project target > Build Setting >Search “Language - c++”
-C ++ Language Dialet = GNU ++11 [-std=gnu++11]
-C ++ standard Library libc++ (LLVM C++ standard with c++ 11 support)


>>.Project target > Build Setting >Always search user path = no
>>.Project target > Build Setting >Build Active Architecture only.
Debug = yes
Distrubiton = no
Release = no

>>After above changes u got error because of below reasons than just replace below 

UITextAlignmentCenter ->NSTextAlignmentCenter
UITextAlignmentLeft
UITextAlignmentRight
kCFDateFormatterMediumStyle - >NSDateFormatterMediumStyle

UILineBreakModeWordWrap ->NSLineBreakByWordWrapping