-1

I'm also beginner for iOS technology. And as per my title saying that might be this question will helpful for each new developer.

So welcome to all edit my answer and correct me OR put your own answer to improve our knowledge.

In the below Example I'm considering

1) One table name is “Student”
2) Below are fields name
- First Name
- Last Name
- Address
- Birth Date

Here we can apply manipulate operation such like “Add”, “Update”, “Delete” and “Fetch” record from the table.

UPDATE :

As per other user's answer we also can mange by CoreData too. But CoreData is faster and easier then SQLite ? If data is complex then how can we manage by CoreData?

Saavaj
  • 109
  • 8
  • I think such kind of questions has number of answers already. There are many tutorials with sample codes for managing database using SQLite,Core Data , Realm etc. If you search on google you can easily find all this stuff. Try those stuff, and still if you don't understand anything in the implementation, then you should ask relevant questions here. – Vishal Sonawane Dec 26 '16 at 12:52

4 Answers4

0

First we need to create SQLite database and table. I’m thinking there are so many way to create database and table but most sufficient way that I’m using

1) Install Firefox and Install Add-ons https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/

2) Create Database
- Go on Firefox -> tools -> SQLite Manager
- Top left corner choose 3rd -> New Database OR On the menu bar, choose “Database” -> New Database
- Give Database name “student” and save right place in your project.

3) Create Table - Left side menu-> select “Tables(0)” -> Right click - Create Table OR On the menu bar, choose “Table” -> Create Table
- Give Table name “student_info” and save right place in your project.

Belo Are the code for execute manipulate operation.

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

@interface SQLDb : NSObject
{
    sqlite3 *_database;
    NSString *savedDate;
}

@property (readwrite) sqlite3* _database;
@property (nonatomic, strong) NSString *savedDate;

+(SQLDb *) initEngine;
+ (SQLDb*) database ;
+(void)releaseEngine;
- (void) executeQuery:(NSString *)query;

-(void) insertRecordInStuentTable:(NSMutableDictionary *) dicOfStudent;
-(NSMutableArray *) getRecordFrom_bannerTable;
-(void)updateNameOfStuden:(NSString *)studentName withRollNumber:(NSString *)strRollNumber;
-(void) deleteAllDataFrom_Student_Table;

And for .m file

#import "SQLDb.h"

@implementation SQLDb

////Getters / Setters
@synthesize _database, savedDate;

static SQLDb* _database = nil;

//start for initialization of database

#pragma mark -  Initialization Methods -

+ (SQLDb*)database
{
    if (_database == nil)
        _database = [[SQLDb alloc] init];

    return _database;
}

+(SQLDb *) initEngine
{
    if ( !_database )
    {
        NSString *databaseName = @“student.sqlite";
        [SQLDb createEditableCopyOfFileIfNeeded:databaseName];
        sqlite3 *db = nil;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:databaseName];
        NSLog(@"DB path - %@", path);
        const char* dbName = [path UTF8String];
        if ( sqlite3_open(dbName,&db) != SQLITE_OK )
        {
            NSException* initException;
            initException = [NSException exceptionWithName:@"SQL Exception" reason:@"Database Initialization Failed" userInfo:nil];
            @throw initException;
        }

        _database = [[self allocWithZone: NULL] init] ;
        _database._database = db;
    }

    return _database;
}

+ (void)createEditableCopyOfFileIfNeeded:(NSString *)fileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:fileName];
    BOOL success = [fileManager fileExistsAtPath:writableDBPath];
    if (success)
        return;

    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];

    NSLog(@"Database Path - %@", writableDBPath);
    if (!success)
        NSLog(@"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}

-(void) executeQuery:(NSString *)query
{
    sqlite3_stmt *statement;
    if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) == SQLITE_OK)
    {
        char *selectQuery = sqlite3_mprintf([query UTF8String]);
        sqlite3_free(selectQuery);
        sqlite3_step(statement);
        sqlite3_finalize(statement);
    }
}

+(void) releaseEngine
{
    sqlite3_close(_database._database);
    _database._database = nil;
    _database = nil;
}


//==================================

-(void) insertBannerInTable:(NSMutableDictionary *) dicOfStuent
{
    int ret;
    const char *sql = "INSERT INTO `student` (‘firstname’, ‘lastname’, ‘bdate’, ‘address’) VALUES (?, ?, ?, ?);";

    sqlite3_stmt *insStmt = NULL;
    if ( !insStmt )
        if ( (ret = sqlite3_prepare_v2(_database, sql, -1, &insStmt, NULL)) != SQLITE_OK ) {

            NSLog(@"Proble to insert record in student");
        }

    // bind values

    sqlite3_bind_text(insStmt, 1, [[NSString stringWithFormat:@"%@", [dicOfStuent objectForKey:@"firstname"]] UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(insStmt, 2, [[NSString stringWithFormat:@"%@", [dicOfStuent objectForKey:@"lastname"]] UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(insStmt, 3, [[NSString stringWithFormat:@"%@", [dicOfStuent objectForKey:@"bdate"]] UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(insStmt, 4, [[NSString stringWithFormat:@"%@", [dicOfStuent objectForKey:@“address”]] UTF8String], -1, SQLITE_TRANSIENT);

    if ((ret = sqlite3_step(insStmt)) != SQLITE_DONE) {NSLog(@"error while inserting data in 'student' table");}
    sqlite3_reset(insStmt);
}


-(NSMutableArray *) getRecordFrom_StudentTable
{
    NSMutableArray *listofStudent = [[NSMutableArray alloc] init];
    sqlite3_stmt *statement = NULL;
    NSString *query = [NSString stringWithFormat:@"SELECT * FROM bannerTable"];
    if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) == SQLITE_OK)
    {
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
            //('banner_id', 'banner_image', 'banner_type', 'banner_description', 'banner_link') VALUES (?, ?, ?, ?, ?)

            char *mainIDChars = (char *) sqlite3_column_text(statement, 0);
            char *bnrIdChars = (char *) sqlite3_column_text(statement, 1);
            char *bnrImgChars = (char *) sqlite3_column_text(statement, 2);
            char *bnrTypChars = (char *) sqlite3_column_text(statement, 3);
            char *bnrDesChars = (char *) sqlite3_column_text(statement, 4);
            char *bnrLinkChars = (char *) sqlite3_column_text(statement, 5);

            NSString *mainID = @"", *advertisement_id  = @"", *advertisement_image = @"", *advertisement_type  = @"", *advertisement_description  = @"", *advertisement_link = @"";

            if(mainIDChars != NULL)
                mainID  = [[NSString alloc] initWithUTF8String:mainIDChars];
            if(bnrIdChars != NULL)
                advertisement_id  = [[NSString alloc] initWithUTF8String:bnrIdChars];
            if(bnrImgChars != NULL)
                advertisement_image  = [[NSString alloc] initWithUTF8String:bnrImgChars];
            if(bnrTypChars != NULL)
                advertisement_type  = [[NSString alloc] initWithUTF8String:bnrTypChars];
            if(bnrDesChars != NULL)
                advertisement_description  = [[NSString alloc] initWithUTF8String:bnrDesChars];
            if(bnrLinkChars != NULL)
                advertisement_link  = [[NSString alloc] initWithUTF8String:bnrLinkChars];

            NSMutableDictionary *dicOfStuent = [[ NSMutableDictionary alloc] init];
            [dicOfStuent setObject:mainID forKey:@"main_id"];
            [dicOfStuent setObject:advertisement_id forKey:@"advertisement_id"];
            [dicOfStuent setObject:advertisement_image forKey:@"advertisement_image"];
            [dicOfStuent setObject:advertisement_type forKey:@"is_image_url"];
            [dicOfStuent setObject:advertisement_description forKey:@"advertisement_description"];
            [dicOfStuent setObject:advertisement_link forKey:@"advertisement_link"];
            [listofStudent addObject:dicOfStuent];
        }
        sqlite3_finalize(statement);
    }

    return listofStudent;
}


-(void)updateNameOfStuden:(NSString *)studentName withRollNumber:(NSString *)strRollNumber
{
    int ret;
    const char *sql = "update user_Group_ChatList set is_online = ? where Jabber_id = ?;";
    sqlite3_stmt *updtStmt = NULL;
    if ( !updtStmt )
        if ( (ret = sqlite3_prepare_v2(_database, sql, -1, &updtStmt, NULL)) != SQLITE_OK ) {}

    // bind values
    sqlite3_bind_text(updtStmt, 1, [[NSString stringWithFormat:@"%@", strProductID] UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(updtStmt, 2, [strTotalProduct UTF8String], -1, SQLITE_TRANSIENT);

    if ((ret = sqlite3_step(updtStmt)) != SQLITE_DONE) {NSLog(@"error while updating  QTY from ProductsCart Table");}
    sqlite3_reset(updtStmt);

}


-(void) deleteAllDataFrom_Student_Table
{
    int ret;
    const char *sql = "DELETE FROM student";

    sqlite3_stmt *dltStmt = NULL;
    if ( !dltStmt )
        if ( (ret = sqlite3_prepare_v2(_database, sql, -1, &dltStmt, NULL)) != SQLITE_OK ) {}

    if ((ret = sqlite3_step(dltStmt)) != SQLITE_DONE) {NSLog(@"Error : While Deleting Record From  user_Group_ChatList Table");}
    sqlite3_reset(dltStmt);
}

Above are .H and .M file that will help you to manage SQLite database.

Saavaj
  • 109
  • 8
0

If you are a beginner to iOS technology and want to learn local storage management then i will suggest you to go with CoreData:

Manage Local storage using Core Data

Because using core data you can interact with local database in a form of object and class.

Dheeraj D
  • 4,386
  • 4
  • 20
  • 34
  • "CoreData" Yes I'm learning that but can you tell me which one is easy and sufficient SQLite or Coredata? – Saavaj Dec 26 '16 at 11:43
  • I must suggest you to go with coredata and if you want to know the advantages of using it then please refer: http://stackoverflow.com/questions/6377274/what-are-some-advantages-of-using-core-data-as-opposed-to-plist – Dheeraj D Dec 26 '16 at 11:45
0

According to your Question most of them say

Coredta is better than SQLite

When you use SQLite using Adds-on tool we need to do the below things.I explain you clearly.

My DB Name is - LoginRegistration.sqlite

My DB Table Name is - TblReg

I have Login Screen.In that I have username and password field.Below that I have Login and Register Button.

When you click register button it goes to registration page view controller where we have to register first then we have to save the data on insert the data into our SQLite db.

For implementing SQLite,first we must add and import the sqlite3.h.

DatabaseOne.h

 #import <Foundation/Foundation.h>
 #import <sqlite3.h>
 @interface DatabaseOne : NSObject{
 sqlite3 *SQLDB;
 NSString *dbName;
 }

 +(DatabaseOne *)sharedDB;

 -(id)init;
 - (id)initWithName:(NSString *)dbname;
 - (void)createDB:(NSString *)dbname;
 - (NSString *)getDBPath;
 - (void)copyDatabaseIfNeeded;
 - (BOOL)executeQuery:(NSString *)query;
 - (NSString*)checkForNull:(char*)colValue;
 - (NSMutableArray *)executeSelectQuery:(NSString *)query;

 @end

DatabaseOne.m

#import "DatabaseOne.h"
@implementation DatabaseOne
static DatabaseOne *shared = nil;

/***
Create a single GSSQL instance
***/

+(DatabaseOne *)sharedDB;
{
@synchronized([DatabaseOne class])
{
    if (!shared) {
        return [[self alloc] init];
    }
    return shared;
}
return nil;
}

-(id)init
{
shared =  [super init];
return shared;

}

-(id)initWithName:(NSString *)dbname;
{
self = [super init];
if (self) {
    dbName =[[NSString alloc] initWithString:dbname];
    [self copyDatabaseIfNeeded];
}
return self;
}



/***
Create a DB on documents with the name you given dbname;
***/

- (void)createDB:(NSString *)dbname;
{
dbName = [[NSString alloc] initWithString:dbname];
[shared copyDatabaseIfNeeded];
}



/***
Get the DB Path of Database exists in documents folder
***/

- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:dbName];
}


/***
Creates and copies the DB from Resources to documents directory
***/

- (void)copyDatabaseIfNeeded {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName];
BOOL isResourceAvail = [fileManager fileExistsAtPath:defaultDBPath];
if (isResourceAvail == NO) {
    NSLog(@"DB %@ is not exists in Resource to be copied",dbName);
}else
{
    BOOL success = [fileManager fileExistsAtPath:dbPath];
    if(!success) {
        NSLog(@"Copying the DB %@", defaultDBPath);
        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

        if (!success)
            NSAssert1(0, @"Failed to copy database: '%@'.", [error localizedDescription]);
    }
}
}


#pragma mark - query execution
/***
Execute the query string(NSString *)
***/

-(BOOL)executeQuery:(NSString *)query;
{
BOOL done = NO;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];

if(success) {
    int sql_results = sqlite3_open([dbPath UTF8String], &SQLDB);

    const char *sql = [query UTF8String];
    if (sql_results == SQLITE_OK) {

        if(sqlite3_exec(SQLDB, sql, nil, nil, nil) == SQLITE_OK) {
            printf("Good SQL\n");
            done = YES;
        }
        else {
            NSLog(@"Bad SQL: %s -- %d", sql,sql_results);
            //NSLog(@"Bad SQL:%d",sql_results);
        }
    }
    else {
        printf("DB Open FAILED\n");
        NSLog(@"error code %i", sql_results);
    }
    sqlite3_close(SQLDB);
}
else {
    printf("DB not exists in application folder\n");
}
return done;
}


/***
Executes select query and returns array of results
***/


-(NSMutableArray *)executeSelectQuery:(NSString *)query
{
NSMutableArray *results = [[NSMutableArray alloc] init];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];

if(success) {
    int sql_results = sqlite3_open([dbPath UTF8String], &SQLDB);
    if (sql_results == SQLITE_OK) {
        const char *sql = [query UTF8String];
        sqlite3_stmt *selectStmt = nil;
        if (sqlite3_prepare_v2(SQLDB, sql, -1, &selectStmt, NULL) == SQLITE_OK) {
            while (sqlite3_step(selectStmt) == SQLITE_ROW) {

                int columnCount = sqlite3_column_count(selectStmt);
                NSMutableDictionary *row = [NSMutableDictionary dictionary];
                for (int i = 0; i < columnCount; i++) {

                    NSString *column_name = [self checkForNull:(char *)sqlite3_column_name(selectStmt, i)];
                    NSString *column_value = [self checkForNull:(char *)sqlite3_column_text(selectStmt, i)];

                    [row setValue:column_value forKey:column_name];
                }
                [results addObject:row];
            }
        }
        sqlite3_reset(selectStmt);
    }
    sqlite3_close(SQLDB);
}
else {
    printf("DB not exists in application folder\n");
}
return results;
}

/***
Checks for a NULL value
***/

- (NSString*)checkForNull:(char*)colValue {

NSString *returnValue = @"something";

if(colValue) {
    returnValue = [NSString stringWithUTF8String:colValue];
}
else {
    returnValue = @"nil";
}
return(returnValue);
}


@end

Now the Modal data are

Register.h

#import <Foundation/Foundation.h>

@interface Register : NSObject


@property (nonatomic,retain) NSString *strFirstName;
@property (nonatomic,retain) NSString *strLastName;
@property (nonatomic,retain) NSString *strEmailId;
@property (nonatomic,retain) NSString *strPassword;
@property (nonatomic,retain) NSString *strMobileNo;
@property (nonatomic,retain) NSString *strMilliSeconds;
@property (nonatomic,retain) NSString *IsRegister;

-(id)init;

@end

Register.m

#import "Register.h"

@implementation Register



@synthesize strPassword = _strPassword;
@synthesize strMobileNo = _strMobileNo;
@synthesize strEmailId  = _strEmailId;
@synthesize strFirstName = _strFirstName;
@synthesize strLastName = _strLastName;
@synthesize strMilliSeconds = _strMilliSeconds;
@synthesize IsRegister = _IsRegister;


-(id)init
{
    self = [super init];
    if (self != nil)
    {
        _strFirstName = [[NSString alloc]init];
        _strEmailId = [[NSString alloc]init];
        _strPassword = [[NSString alloc]init];
        _strLastName = [[NSString alloc]init];
        _strMobileNo = [[NSString alloc]init];
        _strMilliSeconds = [[NSString alloc]init];
        _IsRegister = [[NSString alloc]init];
    }
    return self;

}
@end

Here I set the intermediate for ViewController(RegisterPage)-DataBase

ViewController_DBConnection.h

#import <Foundation/Foundation.h>
#import "Register.h"
#import "DatabaseOne.h"
@interface ViewController_DBConnection : NSObject
+(void)registerDB:(Register *)registerDB;
+(NSMutableArray *)GetRegisterAccount:(NSString *) whereQuery;
+(NSMutableArray *)GetRegisterDetail;
@end

ViewController_DBConnection.m

#import "ViewController_DBConnection.h"

@implementation ViewController_DBConnection

+(void)registerDB:(Register *)registerDB
{
    NSString *query = [[NSString alloc]initWithFormat:@"INSERT into TblReg(Firstname,Lastname,EmailId,Password,Mobileno,Milliseconds)values(\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\")",registerDB.strFirstName,registerDB.strLastName,registerDB.strEmailId,registerDB.strPassword,registerDB.strMobileNo,registerDB.strMilliSeconds];
    BOOL Success = [[DatabaseOne sharedDB]executeQuery:query];
    if(Success)
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"Registration Success" object:nil];
    }

}

+(void)update:(Register *)registerDB
{
   NSString *query = [[NSString alloc]initWithFormat:@"update TblReg Set Firstname = '%@',Lastname = '%@',EmailId = '%@' ,Password = '%@',Mobileno = '%@' WHERE Milliseconds = '%@'",registerDB.strFirstName,registerDB.strLastName,registerDB.strEmailId,registerDB.strPassword,registerDB.strMobileNo,registerDB.strMilliSeconds];
   BOOL Success = [[DatabaseOne sharedDB]executeQuery:query];
   if(Success)
   {
     [[NSNotificationCenter defaultCenter]postNotificationName:@"Updation Success" object:nil];
   }
}

+(NSMutableArray *)GetRegisterAccount:(NSString *) whereQuery
{
    NSString *query=[[NSString alloc]initWithFormat:@"select * from TblReg WHERE %@;", whereQuery];
    NSMutableArray *arrayData = [[DatabaseOne sharedDB]executeSelectQuery:query];
    return arrayData;
}

+(NSMutableArray *)GetRegisterDetail
{
    NSString *query=[[NSString alloc]initWithFormat:@"select * from Register"];
    NSMutableArray *arrayData = [[DatabaseOne sharedDB]executeSelectQuery:query];
    return arrayData;
}

@end

Now my Register View Controller

ViewController.h

#import <UIKit/UIKit.h>
#import "DatabaseOne.h"
#import "ViewController_DBConnection.h"
#import "Register.h"

@interface ViewController : UIViewController<UITextFieldDelegate,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    Register *registerDB;
}
@property (strong, nonatomic) IBOutlet UITextField *firstNameTxtFld;
@property (strong, nonatomic) IBOutlet UITextField *lastNameTextField;
@property (strong, nonatomic) IBOutlet UIImageView *imageViewData;
@property (strong, nonatomic) IBOutlet UITextField *emaiIdTextField;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
@property (strong, nonatomic) IBOutlet UITextField *ConfirmPasswordtextField;
@property (strong, nonatomic) IBOutlet UITextField *mobilenoTextField;
- (IBAction)actionSave:(id)sender;
@end

ViewController.m

#import "ViewController.h"

@interface ViewController (){
    CGFloat animatedDistance;
    NSMutableArray *arrayDBGetData;
}

@end
@implementation ViewController
@synthesize firstNameTxtFld,lastNameTextField,emaiIdTextField,passwordTextField,ConfirmPasswordtextField,mobilenoTextField;

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;

- (void)viewDidLoad {
   [super viewDidLoad];
   // Do any additional setup after loading the view, typically from a nib.

    [[DatabaseOne sharedDB] createDB:@"LoginRegistration.sqlite"];
    arrayDBGetData = [[NSMutableArray alloc]init];
    registerDB = [[Register alloc]init];
}


- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}


//pragma mark - UITextField Dlelgate method
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
      if (![textField isEqual:firstNameTxtFld])  {
        CGRect textViewRect = [self.view.window convertRect:textField.bounds fromView:textField];
        CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
        CGFloat midline = textViewRect.origin.y + 0.5 * textViewRect.size.height;
        CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
        CGFloat denominator =   (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
        CGFloat heightFraction = numerator / denominator;
        if (heightFraction < 0.0)
        {
            heightFraction = 0.0;
        }
        else if (heightFraction > 1.0)
        {
            heightFraction = 1.0;
        }
        animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
        CGRect viewFrame = self.view.frame;
        viewFrame.origin.y -= animatedDistance;
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
        [self.view setFrame:viewFrame];
        [UIView commitAnimations];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
}

- (IBAction)actionSave:(id)sender{

    registerDB.strFirstName = firstNameTxtFld.text;
    registerDB.strLastName = lastNameTextField.text;
    registerDB.strEmailId = emaiIdTextField.text;
    registerDB.strPassword = passwordTextField.text;
    registerDB.strMobileNo = mobilenoTextField.text;

    [self getMilliSeconds];

    arrayDBGetData = [ViewController_DBConnection GetRegisterAccount:[NSString stringWithFormat:@"EmailId = \"%@\"",registerDB.strEmailId]];

    if([firstNameTxtFld.text length]==0||[lastNameTextField.text length]==0 || [emaiIdTextField.text length]==0 || [ConfirmPasswordtextField.text length] ==0 || [mobilenoTextField.text length]==0){
        [self showAlertController:@"Error!" passMessage:@"Please Enter All Fields"];
    }
    else if([self emailValidation:registerDB.strEmailId] == FALSE){
        [self showAlertController:@"Error!" passMessage:@"Please Enter Valid Email Address"];
    }
    else if(![passwordTextField.text isEqualToString:ConfirmPasswordtextField.text]){
        [self showAlertController:@"Error!" passMessage:@"Please Enter matching password"];
    }
    else if([self checkNumeric:registerDB.strMobileNo] == FALSE){
        [self showAlertController:@"Error!" passMessage:@"Please Enter Valid Mobile No"];
    }
    else if([arrayDBGetData count]!=0){
        [self showAlertController:@"Warning !" passMessage:@"Already user have this Email Address.Try New?"];
    }
    else{
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Registration Success" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(registrationSuccess:)
                                                     name:@"Registration Success"
                                                   object:nil];
        [ViewController_DBConnection registerDB:registerDB];
    }


}

//For Checking mail with - example@gmail.com
-(BOOL)checkValidEmail:(NSString *)checkString{
    BOOL stricterFilter = NO;
    NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
    NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:checkString];
}

//For Checking mail with - ex@m.in
- (BOOL)emailValidation:(NSString *)email {
    NSString *emailRegEx =
    @"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
    @"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
    @"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
    @"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
    @"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
    @"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
    @"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";

    NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
    BOOL myStringMatchesRegEx = [regExPredicate evaluateWithObject:[email lowercaseString]];
    return myStringMatchesRegEx;
}

//For checking Mobile No
- (BOOL)checkNumeric:(NSString *)textvalue {
    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithRange:NSMakeRange('0',10)] invertedSet];
    NSString *trimmed = [textvalue stringByTrimmingCharactersInSet:[NSCharacterSet symbolCharacterSet]];
    BOOL isNumeric = trimmed.length > 0 && [trimmed rangeOfCharacterFromSet:nonNumberSet].location == NSNotFound;
    return isNumeric;
}


-(void)getMilliSeconds{
    NSDate *now = [[NSDate alloc] init];
    NSDateFormatter *datetimeFormatter =[[NSDateFormatter alloc]init];
    [datetimeFormatter setDateFormat:@"ddMMyyyyHHmmssSS"];
    registerDB.strMilliSeconds=[datetimeFormatter stringFromDate:now];
}

-(void)showAlertController:(NSString *)title passMessage:(NSString *)message{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)registrationSuccess:(NSNotification *)notification
{
    if([[notification name] isEqualToString:@"Registration Success"]){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Success !" message:@"Registered Successfully" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

@end

Now Finally I check the login screen once I registered successfully.

RootViewController.h

#import <UIKit/UIKit.h>
#import "ViewController_DBConnection.h"

@interface RootViewController : UIViewController<UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField *usernameTextField;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
- (IBAction)actionLogin:(id)sender;
@end

RootViewController.m

#import "RootViewController.h"

@interface RootViewController ()
{
    NSMutableArray *arrayGetDBData;
    CGFloat animatedDistance;
}

@end

@implementation RootViewController

@synthesize usernameTextField,passwordTextField;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[DatabaseOne sharedDB] createDB:@"LoginRegistration.sqlite"];
    arrayGetDBData = [[NSMutableArray alloc]init];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (IBAction)actionLogin:(id)sender {

    //@"Error !" message:@"Username or Password is not correct"
    if([usernameTextField.text length]==0||[passwordTextField.text length]==0){
        [self showAlertController:@"Error!" passMessage:@"Please Enter the missing Fields"];
    }
    else{
        arrayGetDBData = [ViewController_DBConnection GetRegisterAccount:[NSString stringWithFormat:@"Emailid = \"%@\"",usernameTextField.text]];
        if(arrayGetDBData.count==0){
            [self showAlertController:@"Error!" passMessage:@"Username is not correct"];
        }
        else if(![passwordTextField.text isEqualToString:[[arrayGetDBData objectAtIndex:0]valueForKey:@"Password"]])
        {
         [self showAlertController:@"Error!" passMessage:@"Password is not correct"];
        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Success" message:@"Successfully Logged" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){

            }];
            [alert addAction:okAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
}


-(void)showAlertController:(NSString *)title passMessage:(NSString *)message{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark - UITextField Delegate Methods

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.3;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    if (heightFraction < 0.0)
        heightFraction = 0.0;
    else if (heightFraction > 1.0)
        heightFraction = 1.0;
    animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
}
@end

Above I checked everything very clearly.It works perfectly.

Community
  • 1
  • 1
user3182143
  • 9,459
  • 3
  • 32
  • 39
0

Here is my answer for updating and deleting the row from the table view

**DatabaseOne.h**

 #import <Foundation/Foundation.h>
 #import <sqlite3.h>
 @interface DatabaseOne : NSObject{
 sqlite3 *SQLDB;
 NSString *dbName;
 }

 +(DatabaseOne *)sharedDB;

 -(id)init;
 - (id)initWithName:(NSString *)dbname;
 - (void)createDB:(NSString *)dbname;
 - (NSString *)getDBPath;
 - (void)copyDatabaseIfNeeded;
 - (BOOL)executeQuery:(NSString *)query;
 - (NSString*)checkForNull:(char*)colValue;
 - (NSMutableArray *)executeSelectQuery:(NSString *)query;

 @end

DatabaseOne.m

#import "DatabaseOne.h"
@implementation DatabaseOne
static DatabaseOne *shared = nil;

/***
Create a single GSSQL instance
***/

+(DatabaseOne *)sharedDB;
{
@synchronized([DatabaseOne class])
{
    if (!shared) {
        return [[self alloc] init];
    }
    return shared;
}
return nil;
}

-(id)init
{
shared =  [super init];
return shared;

}

-(id)initWithName:(NSString *)dbname;
{
self = [super init];
if (self) {
    dbName =[[NSString alloc] initWithString:dbname];
    [self copyDatabaseIfNeeded];
}
return self;
}



/***
Create a DB on documents with the name you given dbname;
***/

- (void)createDB:(NSString *)dbname;
{
dbName = [[NSString alloc] initWithString:dbname];
[shared copyDatabaseIfNeeded];
}



/***
Get the DB Path of Database exists in documents folder
***/

- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:dbName];
}


/***
Creates and copies the DB from Resources to documents directory
***/

- (void)copyDatabaseIfNeeded {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName];
BOOL isResourceAvail = [fileManager fileExistsAtPath:defaultDBPath];
if (isResourceAvail == NO) {
    NSLog(@"DB %@ is not exists in Resource to be copied",dbName);
}else
{
    BOOL success = [fileManager fileExistsAtPath:dbPath];
    if(!success) {
        NSLog(@"Copying the DB %@", defaultDBPath);
        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

        if (!success)
            NSAssert1(0, @"Failed to copy database: '%@'.", [error localizedDescription]);
    }
}
}


#pragma mark - query execution
/***
Execute the query string(NSString *)
***/

-(BOOL)executeQuery:(NSString *)query;
{
BOOL done = NO;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];

if(success) {
    int sql_results = sqlite3_open([dbPath UTF8String], &SQLDB);

    const char *sql = [query UTF8String];
    if (sql_results == SQLITE_OK) {

        if(sqlite3_exec(SQLDB, sql, nil, nil, nil) == SQLITE_OK) {
            printf("Good SQL\n");
            done = YES;
        }
        else {
            NSLog(@"Bad SQL: %s -- %d", sql,sql_results);
            //NSLog(@"Bad SQL:%d",sql_results);
        }
    }
    else {
        printf("DB Open FAILED\n");
        NSLog(@"error code %i", sql_results);
    }
    sqlite3_close(SQLDB);
}
else {
    printf("DB not exists in application folder\n");
}
return done;
}


/***
Executes select query and returns array of results
***/


-(NSMutableArray *)executeSelectQuery:(NSString *)query
{
NSMutableArray *results = [[NSMutableArray alloc] init];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];

if(success) {
    int sql_results = sqlite3_open([dbPath UTF8String], &SQLDB);
    if (sql_results == SQLITE_OK) {
        const char *sql = [query UTF8String];
        sqlite3_stmt *selectStmt = nil;
        if (sqlite3_prepare_v2(SQLDB, sql, -1, &selectStmt, NULL) == SQLITE_OK) {
            while (sqlite3_step(selectStmt) == SQLITE_ROW) {

                int columnCount = sqlite3_column_count(selectStmt);
                NSMutableDictionary *row = [NSMutableDictionary dictionary];
                for (int i = 0; i < columnCount; i++) {

                    NSString *column_name = [self checkForNull:(char *)sqlite3_column_name(selectStmt, i)];
                    NSString *column_value = [self checkForNull:(char *)sqlite3_column_text(selectStmt, i)];

                    [row setValue:column_value forKey:column_name];
                }
                [results addObject:row];
            }
        }
        sqlite3_reset(selectStmt);
    }
    sqlite3_close(SQLDB);
}
else {
    printf("DB not exists in application folder\n");
}
return results;
}

/***
Checks for a NULL value
***/

- (NSString*)checkForNull:(char*)colValue {

NSString *returnValue = @"something";

if(colValue) {
    returnValue = [NSString stringWithUTF8String:colValue];
}
else {
    returnValue = @"nil";
}
return(returnValue);
}


@end

Now the Modal data are

Register.h

#import <Foundation/Foundation.h>

@interface Register : NSObject


@property (nonatomic,retain) NSString *strFirstName;
@property (nonatomic,retain) NSString *strLastName;
@property (nonatomic,retain) NSString *strEmailId;
@property (nonatomic,retain) NSString *strPassword;
@property (nonatomic,retain) NSString *strMobileNo;
@property (nonatomic,retain) NSString *strMilliSeconds;
@property (nonatomic,retain) NSString *IsRegister;

-(id)init;

@end

Register.m

#import "Register.h"

@implementation Register



@synthesize strPassword = _strPassword;
@synthesize strMobileNo = _strMobileNo;
@synthesize strEmailId  = _strEmailId;
@synthesize strFirstName = _strFirstName;
@synthesize strLastName = _strLastName;
@synthesize strMilliSeconds = _strMilliSeconds;
@synthesize IsRegister = _IsRegister;


-(id)init
{
    self = [super init];
    if (self != nil)
    {
        _strFirstName = [[NSString alloc]init];
        _strEmailId = [[NSString alloc]init];
        _strPassword = [[NSString alloc]init];
        _strLastName = [[NSString alloc]init];
        _strMobileNo = [[NSString alloc]init];
        _strMilliSeconds = [[NSString alloc]init];
        _IsRegister = [[NSString alloc]init];
    }
    return self;

}
@end

Here I set the intermediate for ViewController(RegisterPage)-DataBase

ViewController_DBConnection.h

#import <Foundation/Foundation.h>
#import "Register.h"
#import "DatabaseOne.h"
@interface ViewController_DBConnection : NSObject
+(void)registerDB:(Register *)registerDB;
+(void)update:(Register *)registerDB;
+(void)delete:(Register *)registerDB;
+(NSMutableArray *)GetRegisterAccount:(NSString *) whereQuery;
+(NSMutableArray *)GetRegisterDetail;
@end

ViewController_DBConnection.m

#import "ViewController_DBConnection.h"

@implementation ViewController_DBConnection

+(void)registerDB:(Register *)registerDB
{
    NSString *query = [[NSString alloc]initWithFormat:@"INSERT into TblReg(Firstname,Lastname,EmailId,Password,Mobileno,Milliseconds)values(\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\")",registerDB.strFirstName,registerDB.strLastName,registerDB.strEmailId,registerDB.strPassword,registerDB.strMobileNo,registerDB.strMilliSeconds];
    BOOL Success = [[DatabaseOne sharedDB]executeQuery:query];
    if(Success)
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"Registration Success" object:nil];
    }

}

+(void)update:(Register *)registerDB
{
   NSString *query = [[NSString alloc]initWithFormat:@"update TblReg Set Firstname = '%@',Lastname = '%@',EmailId = '%@' ,Password = '%@',Mobileno = '%@' WHERE Milliseconds = '%@'",registerDB.strFirstName,registerDB.strLastName,registerDB.strEmailId,registerDB.strPassword,registerDB.strMobileNo,registerDB.strMilliSeconds];
   BOOL Success = [[DatabaseOne sharedDB]executeQuery:query];
   if(Success)
   {
     [[NSNotificationCenter defaultCenter]postNotificationName:@"Updation Success" object:nil];
   }
}

+(void)delete:(Register *)registerDB
{
    NSString *query = [[NSString alloc]initWithFormat:@"DELETE FROM TblReg where Milliseconds = '%@'",registerDB.strMilliSeconds];
    BOOL Success = [[DatabaseOne sharedDB]executeQuery:query];
    if(Success)
    {
       [[NSNotificationCenter defaultCenter]postNotificationName:@"Deletion Success" object:nil];
    }
}

+(NSMutableArray *)GetRegisterAccount:(NSString *) whereQuery
{
    NSString *query=[[NSString alloc]initWithFormat:@"select * from TblReg WHERE %@;", whereQuery];
    NSMutableArray *arrayData = [[DatabaseOne sharedDB]executeSelectQuery:query];
    return arrayData;
}

+(NSMutableArray *)GetRegisterDetail
{
    NSString *query=[[NSString alloc]initWithFormat:@"select * from Register"];
    NSMutableArray *arrayData = [[DatabaseOne sharedDB]executeSelectQuery:query];
    return arrayData;
}

@end

EditViewController.h

#import <UIKit/UIKit.h>
#import "DatabaseOne.h"
#import "ViewController_DBConnection.h"
#import "Register.h"


@interface EditViewController : UIViewController{
    Register *registerDB;
}

@property (strong, nonatomic) IBOutlet UITextField *firstnameTxtFld;
@property (strong, nonatomic) IBOutlet UITextField *lastnameTxtFld;
@property (strong, nonatomic) IBOutlet UITextField *emailidTxtFld;
@property (strong, nonatomic) IBOutlet UITextField *passwordTxtFld;
@property (strong, nonatomic) IBOutlet UITextField *mobilenoTxtFld;

@property (strong, nonatomic) NSString *strMilliSeconds;
@property (strong, nonatomic) NSString *strEmailId;

- (IBAction)actionEdit:(id)sender;
- (IBAction)actionBack:(id)sender;
- (IBAction)actionDeleteRow:(id)sender;

EditViewController.m

#import "EditViewController.h"

@interface EditViewController (){
    NSMutableArray *arrayGetDBData;
    CGFloat animatedDistance;
}

@end

@implementation EditViewController

@synthesize firstnameTxtFld,lastnameTxtFld,emailidTxtFld,passwordTxtFld,mobilenoTxtFld,strMilliSeconds,strEmailId;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[DatabaseOne sharedDB] createDB:@"LoginRegistration.sqlite"];
    arrayGetDBData = [[NSMutableArray alloc]init];
    arrayGetDBData = [ViewController_DBConnection GetRegisterAccount:[NSString stringWithFormat:@"EmailId = \"%@\"",strEmailId]];
    registerDB = [[Register alloc]init];

    firstnameTxtFld.text = [[arrayGetDBData objectAtIndex:0]valueForKey:@"Firstname"];
    lastnameTxtFld.text = [[arrayGetDBData objectAtIndex:0]valueForKey:@"Lastname"];
    emailidTxtFld.text = [[arrayGetDBData objectAtIndex:0]valueForKey:@"EmailId"];
    passwordTxtFld.text = [[arrayGetDBData objectAtIndex:0]valueForKey:@"Password"];
    mobilenoTxtFld.text = [[arrayGetDBData objectAtIndex:0]valueForKey:@"Mobileno"];
    registerDB.strMilliSeconds = [[arrayGetDBData objectAtIndex:0]valueForKey:@"Milliseconds"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITextField Delegate Methods

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.3;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    if (heightFraction < 0.0)
        heightFraction = 0.0;
    else if (heightFraction > 1.0)
        heightFraction = 1.0;
    animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
}
//For Checking mail with - ex@m.in
- (BOOL)emailValidation:(NSString *)email {
    NSString *emailRegEx =
    @"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
    @"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
    @"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
    @"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
    @"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
    @"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
    @"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";

    NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
    BOOL myStringMatchesRegEx = [regExPredicate evaluateWithObject:[email lowercaseString]];
    return myStringMatchesRegEx;
}


-(BOOL)isNumeric:(NSString*)inputString{
    NSCharacterSet *charcter =[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
    NSString *filtered;
    filtered = [[inputString componentsSeparatedByCharactersInSet:charcter] componentsJoinedByString:@""];
    return [inputString isEqualToString:filtered];
}


- (BOOL)checkNumeric:(NSString *)textvalue {
    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithRange:NSMakeRange('0',10)] invertedSet];
    NSString *trimmed = [textvalue stringByTrimmingCharactersInSet:[NSCharacterSet symbolCharacterSet]];
    BOOL isNumeric = trimmed.length > 0 && [trimmed rangeOfCharacterFromSet:nonNumberSet].location == NSNotFound;
    return isNumeric;
}


-(void)getMilliSeconds{
    NSDate *now = [[NSDate alloc] init];
    NSDateFormatter *datetimeFormatter =[[NSDateFormatter alloc]init];
    [datetimeFormatter setDateFormat:@"ddMMyyyyHHmmssSS"];
    registerDB.strMilliSeconds=[datetimeFormatter stringFromDate:now];
}

-(void)showAlertController:(NSString *)title passMessage:(NSString *)message{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}

- (IBAction)actionEdit:(id)sender {
    registerDB.strFirstName = firstnameTxtFld.text;
    registerDB.strLastName = lastnameTxtFld.text;
    registerDB.strEmailId = emailidTxtFld.text;
    registerDB.strPassword = passwordTxtFld.text;
    registerDB.strMobileNo = mobilenoTxtFld.text;

    arrayGetDBData = [ViewController_DBConnection GetRegisterAccount:[NSString stringWithFormat:@"EmailId = \"%@\"",registerDB.strEmailId]];

    if([firstnameTxtFld.text length]==0 || [lastnameTxtFld.text length]==0 || [emailidTxtFld.text length]==0 ||  [mobilenoTxtFld.text length]==0 ||  [passwordTxtFld.text length]==0){
        [self showAlertController:@"Error!" passMessage:@"Please Enter All Fields"];
    }
    else if([self emailValidation:registerDB.strEmailId] == FALSE){
        [self showAlertController:@"Error!" passMessage:@"Please Enter Valid Email Address"];
    }
    else if([self checkNumeric:registerDB.strMobileNo] == FALSE){
        [self showAlertController:@"Error!" passMessage:@"Please Enter Valid Mobile No"];
    }
    else if([arrayGetDBData count]!=0){
        [self showAlertController:@"Warning !" passMessage:@"Already user have this Email Address.Try New?"];
    }
    else{
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Updation Success" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(updationSuccess:)
                                                     name:@"Updation Success"
                                                   object:nil];
        [ViewController_DBConnection update:registerDB];
    }
}

- (IBAction)actionDeleteRow:(id)sender
{
    registerDB.strFirstName = firstnameTxtFld.text;
    registerDB.strLastName = lastnameTxtFld.text;
    registerDB.strEmailId = emailidTxtFld.text;
    registerDB.strPassword = passwordTxtFld.text;
    registerDB.strMobileNo = mobilenoTxtFld.text;

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Deletion Success" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(deletionSuccess:)
                                                 name:@"Deletion Success"
                                               object:nil];
    [ViewController_DBConnection delete:registerDB];
}
- (IBAction)actionBack:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)updationSuccess:(NSNotification *)notification
{
    if([[notification name] isEqualToString:@"Updation Success"])
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Success !" message:@"Updated Successfully" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

-(void)deletionSuccess:(NSNotification *)notification
{
    if([[notification name] isEqualToString:@"Deletion Success"])
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Success !" message:@"Deleted Successfully" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}
@end
user3182143
  • 9,459
  • 3
  • 32
  • 39