mardi 24 novembre 2015

Retrieve database in ViewController from another ViewController Objective C

I'm so new in Objective C and Xcode. I have a question. Is's possible to retrieve same sqlite database from two different view controller. Here is my plan, try to create simple authentication login. I have four VCs: ViewController, RegisterViewController, LoginViewController, and WelcomeViewController. The idea is, when I click register and go to RegisterViewController, the database's is created. Then I enter intfo in textfields to save in the database. Then when I want to login by email in LoginViewController, I m not sure that I can use the same code to "SELECT * FROM" database which created by another view. When the login is completed (email is matched), it should go to another view controller, LoginViewController, and show first name, and last name. I really need your help, and suggestion guys. Also, any resources that can improve my understanding please!!

RegisterViewController:

#import "RegisterViewController.h"
#import <sqlite3.h>
@interface RegisterViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *txtFname;
@property (weak, nonatomic) IBOutlet UITextField *txtLname;
@property (weak, nonatomic) IBOutlet UITextField *txtEmailID;
@property (weak, nonatomic) IBOutlet UITextField *txtPhone;
@property (weak, nonatomic) IBOutlet UITextField *txtAddress;
@property(nonatomic,strong)NSString *databasePath;
@property(nonatomic)sqlite3 *contactDB;
@end

NSString * docDict;
NSArray * dirPath;

@implementation RegisterViewController
-(void)viewDidLoad
{
    [super viewDidLoad];
    [self.txtFname becomeFirstResponder];
    dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docDict = [dirPath objectAtIndex:0];
    _databasePath = [[NSString alloc]initWithString:[docDict stringByAppendingString:@"UserInfo.sqlite"]];

    if([[NSFileManager defaultManager] fileExistsAtPath:_databasePath] == NO)
    {
        if (sqlite3_open([_databasePath UTF8String], &_contactDB)==SQLITE_OK)
        {
            char *error;
            const char *sql_statement = "create table contacts(firstname text,lastname,emailID text,ph text, address text)";
            if (sqlite3_exec(_contactDB, sql_statement, nil, nil, &error)) {
                UIAlertController * alertcontroller =[UIAlertController alertControllerWithTitle:@"Alert" message:@"Failed to create the table" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *okBtn = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];

                [alertcontroller addAction:okBtn];
                [self presentViewController:alertcontroller animated:YES completion:nil];

            }
            sqlite3_close(_contactDB);

        }
    }


}
-(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
- (IBAction)btnAction_Register:(id)sender {
       sqlite3_stmt *stmt;
    if (sqlite3_open([_databasePath UTF8String],&_contactDB)==SQLITE_OK) {
        NSString * insertSql = [NSString stringWithFormat:@"insert into contacts(firstname,lastname,emailID,ph,address)values(\"%@\",\"%@\",\"%@\",\"%@\",\"%@\")",_txtFname.text,_txtLname.text,_txtEmailID.text,_txtPhone.text,_txtAddress];
        const char * insert_statement = [insertSql UTF8String];
        sqlite3_prepare(_contactDB, insert_statement, -1, &stmt, nil);

        if (sqlite3_step(stmt)== SQLITE_DONE) {
            self.txtAddress.text =@"";
            self.txtEmailID.text = @"";
            self.txtFname.text = @"";
           self.txtLname.text = @"";
            self.txtPhone.text = @"";
            UIAlertController * alertcontroller =[UIAlertController alertControllerWithTitle:nil message:@"Contact Added" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okBtn = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];

            [alertcontroller addAction:okBtn];
            [self presentViewController:alertcontroller animated:YES completion:nil];

        }
        else
        {
            [self displayAlertView:@"Failed to update the contact"];


        }
        sqlite3_finalize(stmt);
        sqlite3_close(_contactDB);


    }

}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    [textField resignFirstResponder];
    return YES;
}

#pragma mark Validation
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if ([textField isEqual:self.txtEmailID])
    {
        BOOL status = [self validateEmailWithString:self.txtEmailID.text];
        if (!status)
        {
            [self displayAlertView:@"Enter Valied Email-ID"];
            return NO;
        }

    }
    return YES;
}

- (BOOL)validateEmailWithString:(NSString*)email

{

    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    return [emailTest evaluateWithObject:email];

}

-(void)displayAlertView:(NSString *)message

{

    UIAlertController *alertCont =[UIAlertController alertControllerWithTitle:@"Alert" message:message preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];

    [alertCont addAction:okAction];

    [self presentViewController:alertCont animated:YES completion:nil];



}

@end

LoginViewController :

#import "LogInViewController.h"
#import "RegisterViewController.h"
#import "WelcomeViewController.h"
#import <sqlite3.h>
@interface  LogInViewController ()
@property (weak, nonatomic) IBOutlet UITextField *txtLogInEmailID;
@property(nonatomic,strong)NSString *databasePath;
@property(nonatomic)sqlite3 *contactDB;
@property(nonatomic,strong)NSString * fname;
@property(nonatomic,strong)NSString * lname;



@end
@implementation LogInViewController
-(void)viewDidLoad
{
    [self.txtLogInEmailID becomeFirstResponder];
}
- (IBAction)btnAction_Login:(id)sender {
    sqlite3_stmt *stmt;
    const char *dbpath =[_databasePath UTF8String];
    if (sqlite3_open(dbpath, &_contactDB)==SQLITE_OK) {
        NSString *querySQL = [NSString stringWithFormat:
                              @"SELECT emailID FROM contacts WHERE emailID=\"%@\"",
                              _txtLogInEmailID.text];
        const char *query_stmt = [querySQL UTF8String];
        if (sqlite3_prepare_v2(_contactDB, query_stmt, -1, &stmt, nil)) {
            if (sqlite3_step(stmt)==SQLITE_OK) {

                NSString *fname = [[NSString alloc]
                                          initWithUTF8String:
                                          (const char *) sqlite3_column_text(
                                                                             stmt, 0)];

                NSString *lname = [[NSString alloc]
                                        initWithUTF8String:(const char *)
                                        sqlite3_column_text(stmt, 1)];
                fname = self.fname;
                lname= self.lname;

                UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:@"Data Found" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];

                [alertController addAction:okAction];

                [self presentViewController:alertController animated:YES completion:nil];

            }
            [self displayAlertView:@"Data Not Found"];
            sqlite3_finalize(stmt);
        }
        sqlite3_close(_contactDB);

    }


}

#pragma mark Segue
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"login"]) {
        WelcomeViewController *wo = [segue destinationViewController];
        wo.firstName = self.fname;
        wo.lastName = self.lname;
    }
}





- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    [textField resignFirstResponder];
    return YES;
}
#pragma mark Validation
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if ([textField isEqual:_txtLogInEmailID]) {
        BOOL status = [self validateEmailWithString:_txtLogInEmailID.text];
        if (!status)
        {
            [self displayAlertView:@"Enter Valied Email-ID"];
            return NO;
        }

    }
    return YES;
}

- (BOOL)validateEmailWithString:(NSString*)email

{

    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    return [emailTest evaluateWithObject:email];

}

-(void)displayAlertView:(NSString *)message

{

    UIAlertController *alertCont =[UIAlertController alertControllerWithTitle:@"Alert" message:message preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];

    [alertCont addAction:okAction];

    [self presentViewController:alertCont animated:YES completion:nil];



}

@end

WelcomeViewController :

#import "WelcomeViewController.h"

@interface WelcomeViewController()

@property (weak, nonatomic) IBOutlet UILabel *lblfname;
@property (weak, nonatomic) IBOutlet UILabel *lblLname;

@end
@implementation WelcomeViewController
-(void)viewDidLoad
{
    [super viewDidLoad];
    _lblfname.text = self.firstName;
    _lblLname.text = self.lastName;
}
- (IBAction)btnAction_logout:(id)sender {
    _lblfname.text = @"";
    _lblLname.text = @"";
}

@end

Aucun commentaire:

Enregistrer un commentaire