Wednesday, 25 February 2015

INNER JOIN Database

INNER JOIN Database 


This Demo Used To Save Data in Different Table and also Get This Data of Database


1) Open the Build Phases tab, and within Link Binary with Libraries, add the following frameworks:

 -libsqlite3.dylib

2) create Sqlite3 Object In your view .h file for using like that ..

#import <sqlite3.h>

3) Create Database :

in Database create Two Table And Take empid as a Common to Get Data
table 1 is Look Like This :



table 2 is Look Like This :




 

Add Your Database to Bundle :

go to Build Phase > Copy Bundle Resources

In "viewcontroller.m" File we create database first and also find the path using "NSSearchpathfordocumentdirectory" method . In "viewdidload" method put This code.

THIS IS COPY TO VIEWCONTROLLER.M (VIEWDIDLOAD METHOD) :



 NSString *docsDir;
    
    NSArray *dirPaths ;
    
    dirPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);  // Get the documents directory
    
    docsDir = dirPaths[0];
    
    
    databasePath = [[NSString alloc]initWithString: [docsDir stringByAppendingPathComponent:@"data.sqlite"]];  // Build the path to the database file





This code is useful for the copy file NSBundle  to the NSDocument directory folder. But First Check the file is available in bundle or not ..?

THIS IS COPY TO APPDELEGATE.M :-



 NSString *pathsToReources = [[NSBundle mainBundle] resourcePath];
    NSString *yourOriginalDatabasePath = [pathsToReources stringByAppendingPathComponent:@"data.sqlite"];
    
    NSArray *pathsToDocuments = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [pathsToDocuments objectAtIndex: 0];
    
    NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"data.sqlite"];
    
    if (![[NSFileManager defaultManager] isReadableFileAtPath: dbPath]) {
        
        if ([[NSFileManager defaultManager] copyItemAtPath: yourOriginalDatabasePath toPath: dbPath error: NULL] != YES)
            
            NSAssert2(0, @"Fail to copy database from %@ to %@", yourOriginalDatabasePath, dbPath);
        
        
    }




4) Make Your Storyboard Like This :



5) Write Coding Which Is given Below :

ViewController (use For Registration View) :
ViewController.h :

#import <UIKit/UIKit.h>
#import <sqlite3.h>
#import "SecViewController.h"

@interface ViewController : UIViewController

@property(strong,nonatomic)IBOutlet UITextField *txtid;
@property(strong,nonatomic)IBOutlet UITextField *txtname;
@property(strong,nonatomic)IBOutlet UITextField *txtno;
@property(strong,nonatomic)IBOutlet UITextField *txtsal;
@property(strong,nonatomic)IBOutlet UITextField *txtdep;

@property (nonatomic) sqlite3 *contactDB;

@property (strong, nonatomic) NSString *databasePath;

@property(strong,nonatomic)SecViewController *secobj;

-(IBAction)dataregister:(id)sender;
-(IBAction)datashow:(id)sender;

@end

ViewController.m :

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize txtdep,txtid,txtname,txtno,txtsal;
@synthesize contactDB,databasePath;
@synthesize secobj;

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *docsDir;
    
    NSArray *dirPaths ;
    
    dirPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);  // Get the documents directory
    
    docsDir = dirPaths[0];
    
    
    databasePath = [[NSString alloc]initWithString: [docsDir stringByAppendingPathComponent:@"data.sqlite"]];  // Build the path to the database file
}

-(IBAction)dataregister:(id)sender
{
    sqlite3_stmt  *statement;
    sqlite3_stmt  *statement1;
    
    const char *dbpath = [databasePath UTF8String];
    
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
        
    {
        NSString *insertSQL = [NSString stringWithFormat:
                             
                             @"INSERT INTO register (empid, empname, empno) VALUES (\"%@\", \"%@\", \"%@\")",self.txtid.text, self.txtname.text, self.txtno.text];
        
        
        const char *insert_stmt = [insertSQL UTF8String];
        
        sqlite3_prepare_v2(contactDB, insert_stmt,
                           
                           -1, &statement, NULL);
        
        // coding for second table
        
        NSString *insertSQL1 = [NSString stringWithFormat:
                               
                               @"INSERT INTO empdata (empid, empsal, empdep) VALUES (\"%@\", \"%@\", \"%@\")",self.txtid.text, self.txtsal.text, self.txtdep.text];
        
        
        const char *insert_stmt1 = [insertSQL1 UTF8String];
        
        sqlite3_prepare_v2(contactDB, insert_stmt1,
                           
                           -1, &statement1, NULL);
        // coding Complate
        
        if (sqlite3_step(statement) == SQLITE_DONE)
            
        {
            if (sqlite3_step(statement1) == SQLITE_DONE)
            {
                UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Hello World!"  message:@"Data Saved"
                                                                 delegate:nil
                                                        cancelButtonTitle:@"OK"
                                                        otherButtonTitles:nil];
                
                [message show];

            }
            else
            {
                UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Hello World!"  message:@"Data Not Saved"
                                                                 delegate:nil
                                                        cancelButtonTitle:@"OK"
                                                        otherButtonTitles:nil];
            
            [message show];
                
            }
            
            
        }
        else
        {
            
            UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Hello World!"  message:@"Data Not Saved"
                                                             delegate:nil
                                                    cancelButtonTitle:@"OK"
                                                    otherButtonTitles:nil];
            
            [message show];
            
        }
        
        sqlite3_finalize(statement);
        sqlite3_finalize(statement1);
        
        sqlite3_close(contactDB);
        
    }
}
-(IBAction)datashow:(id)sender
{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    secobj = [story instantiateViewControllerWithIdentifier:@"SecViewController"];
    
    [self.navigationController pushViewController:secobj animated:YES];
    
}

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

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

@end


SecViewController (use For Show Data in View) :
SecViewController.h :

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

@interface SecViewController : UIViewController

@property(strong,nonatomic)IBOutlet UITextField *txtsearchname;

@property(strong,nonatomic)IBOutlet UILabel *lblname;
@property(strong,nonatomic)IBOutlet UILabel *lblno;
@property(strong,nonatomic)IBOutlet UILabel *lblsal;
@property(strong,nonatomic)IBOutlet UILabel *lbldep;

@property (nonatomic) sqlite3 *contactDB;

@property (strong, nonatomic) NSString *databasePath;


-(IBAction)searchdata:(id)sender;

@end


SecViewController.m :


#import "SecViewController.h"

@interface SecViewController ()

@end

@implementation SecViewController
@synthesize lbldep,lblname,lblno,lblsal;
@synthesize contactDB,databasePath;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSString *docsDir;
    
    NSArray *dirPaths ;
    
    dirPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);  // Get the documents directory
    
    docsDir = dirPaths[0];
    
    
    databasePath = [[NSString alloc]initWithString: [docsDir stringByAppendingPathComponent:@"data.sqlite"]];  // Build the path to the database file

}

-(IBAction)searchdata:(id)sender
{
    const char *dbpath = [databasePath UTF8String];
    
    sqlite3_stmt    *statement;
    
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
        
    {
        
        NSString *querySQL = [NSString stringWithFormat:
                              
                              @"SELECT register.empname, register.empno, empdata.empsal, empdata.empdep FROM register INNER JOIN empdata ON register.empid=empdata.empid WHERE register.empid=\"%@\"",self.txtsearchname.text];
        
        const char *query_stmt = [querySQL UTF8String];
        
        if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
            
        {
            
            if (sqlite3_step(statement) == SQLITE_ROW)
                
            {
                
                NSString *addressField = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text( statement, 0)];
                
                lblname.text = addressField;
                
                
                
            NSString *nofield = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text( statement, 1)];
                
                lblno.text = nofield;
                
            NSString *salary = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text( statement, 2)];
                
                lblsal.text = salary;
                
            NSString *depart = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text( statement, 3)];
                
                lbldep.text = depart;

                
                
                
                UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Hello World!"  message:@"Data Seached"
                                                                 delegate:nil
                                                        cancelButtonTitle:@"OK"
                                                        otherButtonTitles:nil];
                [message show];
                
            }
            else
            {
                
                UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Hello World!"  message:@"Data Not Searched"
                                                                 delegate:nil
                                                        cancelButtonTitle:@"OK"
                                                        otherButtonTitles:nil];
                [message show];
                
            }
            
            sqlite3_finalize(statement);
            
        }
        
        sqlite3_close(contactDB);
        
    }
}

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

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

@end

Indexed TableView

Indexed Table View


1) Set Your Storyboard Like This :



2) Write This Code in ViewController.m :

#import "AnimalTableTableViewController.h"

@interface AnimalTableTableViewController ()
{
    NSDictionary *animals;
    NSArray *animalSectionTitles;
}

@end

@implementation AnimalTableTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    animals = @{@"B" : @[@"Bear", @"Black Swan", @"Buffalo"],
                @"C" : @[@"Camel", @"Cockatoo"],
                @"D" : @[@"Dog", @"Donkey"],
                @"E" : @[@"Emu"],
                @"G" : @[@"Giraffe", @"Greater Rhea"],
                @"H" : @[@"Hippopotamus", @"Horse"],
                @"K" : @[@"Koala"],
                @"L" : @[@"Lion", @"Llama"],
                @"M" : @[@"Manatus", @"Meerkat"],
                @"P" : @[@"Panda", @"Peacock", @"Pig", @"Platypus", @"Polar Bear"],
                @"R" : @[@"Rhinoceros"],
                @"S" : @[@"Seagull"],
                @"T" : @[@"Tasmania Devil"],
                @"W" : @[@"Whale", @"Whale Shark", @"Wombat"]};
    
    animalSectionTitles = [[animals allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    
}

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

- (NSString *)getImageFilename:(NSString *)animal
{
    NSString *imageFilename = [[animal lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@"_"];
    imageFilename = [imageFilename stringByAppendingString:@".jpg"];
    
    return imageFilename;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [animalSectionTitles count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [animalSectionTitles objectAtIndex:section];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *sectionTitle = [animalSectionTitles objectAtIndex:section];
    NSArray *sectionAnimals = [animals objectForKey:sectionTitle];
    return [sectionAnimals count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    // Configure the cell...
    NSString *sectionTitle = [animalSectionTitles objectAtIndex:indexPath.section];
    NSArray *sectionAnimals = [animals objectForKey:sectionTitle];
    NSString *animal = [sectionAnimals objectAtIndex:indexPath.row];
    cell.textLabel.text = animal;
    cell.imageView.image = [UIImage imageNamed:[self getImageFilename:animal]];
    
    return cell;
}


@end

Voice Recoding

Voice Recoding


1) ADD Framework :

- AVFoundation.Framework

2) Put Three Button in Storyboard :



3) Write Coding in ViewController.h :


#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController<AVAudioPlayerDelegate,AVAudioRecorderDelegate>

@property(strong,nonatomic)IBOutlet UIButton *recordpausebutton;

@property(strong,nonatomic)IBOutlet UIButton *stopbutton;

@property(strong,nonatomic)IBOutlet UIButton *playbutton;


-(IBAction)recordpausebutton:(id)sender;
-(IBAction)stopbutton:(id)sender;
-(IBAction)playbutton:(id)sender;

@end



4) Write Coding in ViewController.m :




#import "ViewController.h"

@interface ViewController ()

{
    AVAudioRecorder *recorder;
    AVAudioPlayer *player;
}

@end

@implementation ViewController
@synthesize stopbutton,playbutton,recordpausebutton;


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Disable Stop/Play button when application launches
    [stopbutton setEnabled:NO];
    [playbutton setEnabled:NO];
    
    // Set the audio file
    NSArray *pathComponents = [NSArray arrayWithObjects:
                               [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
                               @"MyAudioMemo.m4a",
                               nil];
    NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
    
    // Setup audio session
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    
    // Define the recorder setting
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
    
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
    
    // Initiate and prepare the recorder
    recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:NULL];
    recorder.delegate = self;
    recorder.meteringEnabled = YES;
    [recorder prepareToRecord];
    
    
}

-(IBAction)recordpausebutton:(id)sender
{
    // Stop the audio player before recording
    if (player.playing) {
        [player stop];
    }
    
    if (!recorder.recording) {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];
        
        // Start recording
        [recorder record];
        [recordpausebutton setTitle:@"Pause" forState:UIControlStateNormal];
        
    } else {
        
        // Pause recording
        [recorder pause];
        [recordpausebutton setTitle:@"Record" forState:UIControlStateNormal];
    }
    
    [stopbutton setEnabled:YES];
    [playbutton setEnabled:NO];
}
-(IBAction)stopbutton:(id)sender
{
    [recorder stop];
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setActive:NO error:nil];
}
-(IBAction)playbutton:(id)sender
{
    if (!recorder.recording){
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil];
        [player setDelegate:self];
        [player play];
    }
}

- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag{
    [recordpausebutton setTitle:@"Record" forState:UIControlStateNormal];
    
    [stopbutton setEnabled:NO];
    [playbutton setEnabled:YES];
}

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Done"
                                                    message: @"Finish playing the recording!"
                                                   delegate: nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}

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

@end

Monday, 23 February 2015

Property List

Property List (PList)


1) add Property List in The Project :



2) add This Type of Data in PList :

When prompted, use “recipes” as the file name. Once you confirm, Xcode will create the property list file for you. By default, the property list is empty.



There are two ways to edit the property list. You can right-click on the editing area and select “Add Row” to add a new value.
Xcode Property List Add Row
Add a New Row in Property List Editor
As we’re going to put the three data arrays in the property list, we’ll add three rows with “array” type. Name them with the keys: RecipeName, Thumbnail and PrepTime. The key serves as an identifier and later you’ll use it in your code to pick the corresponding array.
SimpleTableApp Property List Array
Define Three Arrays in Property List
To add data in the array, just expand it and click the “+” icon to add a new item. Follow the steps in the below illustration if you don’t know how to do it.
Add Property in Property List
Step by Step Procedures to Add an Item in Array
Repeat the procedures until you add all the values for the array. Your property list should look like this:
SimpleTableApp Recipe Property List
Recipe Property List
For your convenience, you may download the recipes.plist and add it to your project.
As mentioned earlier, the property list is usually saved in the format of XML. To view the source of the property list, right click and select “Open as Source Code”.
Open Property List as Source Code
View the Source Code of Property List
The source code of “recipes.plist” file will appear like this:
Property List Source Code
Source Code of Recipes.plist

3) Write Coding Which is Given Below :

Main.Storyboard :



ViewController.h :

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property(strong,nonatomic)IBOutlet UITableView *tblobj;

@property(strong,nonatomic)NSMutableArray *arrrecipe;
@property(strong,nonatomic)NSMutableArray *arrthumbail;
@property(strong,nonatomic)NSMutableArray *arrtime;

@end

ViewController.m :


#import "ViewController.h"
#import "CustomCell.h"




@interface ViewController ()

@end

@implementation ViewController
@synthesize arrrecipe,arrthumbail,arrtime,tblobj;

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"reciepy" ofType:@"plist"];
    
    NSDictionary *dec = [[NSDictionary alloc]initWithContentsOfFile:path];
    
    arrrecipe = [dec objectForKey:@"RecipeName"];
    arrthumbail = [dec objectForKey:@"Thumbail"];
    arrtime = [dec objectForKey:@"PreTime"];
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arrrecipe.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cell = [tblobj dequeueReusableCellWithIdentifier:@"cell"];
    
    cell.objdata.image = [UIImage imageNamed:[arrthumbail objectAtIndex:indexPath.row]];
    cell.namedata.text = [arrrecipe objectAtIndex:indexPath.row];
    cell.timedata.text = [arrtime objectAtIndex:indexPath.row];
    
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You Select" message:[arrrecipe objectAtIndex:indexPath.row] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
    
    [alert show];
    
    
}

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

@end


CustomCell.h :

#import <UIKit/UIKit.h>

@interface CustomCell : UITableViewCell

@property(strong,nonatomic)IBOutlet UIImageView *objdata;
@property(strong,nonatomic)IBOutlet UILabel *namedata;
@property(strong,nonatomic)IBOutlet UILabel *timedata;

@end

CustomCell.m :

#import "CustomCell.h"

@implementation CustomCell
@synthesize objdata,namedata,timedata;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end