A9628298AF2F97B5E073C680D9D5DC85 Apps King Technologies: April 2014

Tuesday 22 April 2014

Sqlite database iOS application

                                     Read and write in to sqlite database in iOS application

//-----add two framework in your project---
1. libsqlite3.dylib
2. libsqlite3.0.dylib


DBManager.h


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

@interface DBManager : NSObject
{
    NSString *databasePath;
}

+(DBManager*)getSharedInstance;
-(BOOL)createDB;
- (BOOL) saveData:(NSString*)ID name:(NSString*)Name address:(NSString*)Address phone:(NSString*)Phone;
- (NSArray*) findByRegisterNumber:(NSString*)ID;
@end




DBManager.m


#import "DBManager.h"
static DBManager *sharedInstance = nil;
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;

@implementation DBManager

+(DBManager *)getSharedInstance
{
    if (!sharedInstance) {
        sharedInstance = [[DBManager alloc]init]; //[[super allocWithZone:NULL]init];
        [sharedInstance createDB];
    }
    return sharedInstance;
}

-(BOOL)createDB
{
    
    NSString *docsDir;
    NSArray *dirPaths;
    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = dirPaths[0];
    // Build the path to the database file
    databasePath = [[NSString alloc] initWithString:
                    [docsDir stringByAppendingPathComponent: @"Contacts.sqlite"]];
    BOOL isSuccess = YES;
    NSFileManager *filemgr = [NSFileManager defaultManager];
    if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
        const char *dbpath = [databasePath UTF8String];
        if (sqlite3_open(dbpath, &database) == SQLITE_OK)
        {
            //char *errMsg;
            //const char *sql_stmt = @"";
           // "create table if not exists studentsDetail (regno integer
           // primary key, name text, department text, year text)";
           // if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)!= SQLITE_OK)
           // {
           //     isSuccess = NO;
           //     NSLog(@"Failed to create table");
           // }
           // sqlite3_close(database);
            return  isSuccess;
        }
        else {
            isSuccess = NO;
            NSLog(@"Failed to open/create database");
        }
    }
    return isSuccess;
}



- (BOOL) saveData:(NSString*)ID
       name:(NSString*)Name address:(NSString*)Address phone:(NSString*)Phone
{
     sqlite3_stmt *statement = nil;
    const char *dbpath = [databasePath UTF8String];
    if (sqlite3_open(dbpath, &database) == SQLITE_OK)
    {
        //NSString *insertSQL = [NSString stringWithFormat:@"insert into Records (id,name, address, phone) values (\"%@\",\"%@\", \"%@\", \"%@\")",ID, Name, Address, Phone];
        
        NSString *insertSQL = [NSString stringWithFormat:@"insert into Records (id,name, address, phone) values ('%@','%@', '%@', '%@');",ID, Name, Address, Phone];
        const char *insert_stmt = [insertSQL UTF8String];
        //sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
        //if (sqlite3_step(statement) == SQLITE_DONE)
        if (sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL) == SQLITE_DONE)
        {
            return YES;
        }
        else {
            return NO;
        }
        sqlite3_reset(statement);
        sqlite3_finalize(statement);
    }
    return NO;
}
                               
- (NSArray*) findByRegisterNumber:(NSString*)ID
  {
    const char *dbpath = [databasePath UTF8String];
    if (sqlite3_open(dbpath, &database) == SQLITE_OK)
    {
        NSString *querySQL = [NSString stringWithFormat:@"select name, address, phone FROM Records where id=\"%@\"",ID];
        const char *query_stmt = [querySQL UTF8String];
        NSMutableArray *resultArray = [[NSMutableArray alloc]init];
        if (sqlite3_prepare_v2(database,query_stmt, -1, &statement, NULL) ==SQLITE_OK)
        {
            if (sqlite3_step(statement) == SQLITE_ROW)
            {
                NSString *name = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
                [resultArray addObject:name];
                NSString *address = [[NSString alloc] initWithUTF8String:
                (const char *) sqlite3_column_text(statement, 1)];
                [resultArray addObject:address];
                 NSString *phone = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)];
                [resultArray addObject:phone];
                return resultArray;
             }
             else{
                    NSLog(@"Not found");
                    return nil;
            }
            sqlite3_reset(statement);
        }
     }
     return nil;
  }

@end




Then go to your view controller.m and call these methods

//-----to save data in database--------
[[DBManager getSharedInstance]saveData:txtFID.text name:txtFName.text address:txtFAddress.text phone:txtFPhone.text];


//------to get data from data base------------
[[DBManager getSharedInstance]findByRegisterNumber:txtFID.text];




Some useful methods and links for storyboard.


Some useful methods in for storyboard.

                                 get object of a class that is push in storyboard.

ProviderLookupViewController* vc = [self.storyboard instantiateViewControllerWithIdentifier:@"ProviderLookupViewController"];
[self presentModalViewController:vc animated:YES];


//--------------------------------------------
[self performSegueWithIdentifier:@"SomeSegueName" sender:someObject];




//--------------------------------

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"TargetSegue"]) {
        TargetViewController *vc = segue.destinationViewController;
        //vc.items = nil;
    }
}



//----------------------------------------------
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"articleView"])
    {
        WebViewController *controller = (WebViewController *)segue.destinationViewController;
        RSSEntry *entry = [_allEntries objectAtIndex:[self.tableView indexPathForSelectedRow].row];
        controller.entry = entry;
    }
}


- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {  
    [self performSegueWithIdentifier:@"articleView" sender:[self.tableView cellForRowAtIndexPath:indexPath]];
}


//****************************************************************

                                   Links to learn storyboard


//****************************************************************