Translate

Sunday, September 23, 2012

Simple sqlite tutorial

Simple sqlite tutorial

First we have to add libsqlite3.0.dylib

sqliteAppDelegate.h


#import <UIKit/UIKit.h>
#import <sqlite3.h> // Import the SQLite database framework

@interface SQLiteTutorialAppDelegate : NSObject  {
    UIWindow *window;
    //UINavigationController *navigationController;
UITabBarController *tabController;
// Database variables
NSString *databaseName;
NSString *databasePath;
// Array to store the animal objects
NSMutableArray *animals;
    
    NSArray *countArray;

}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITabBarController *tabController;
@property (nonatomic, retain) NSMutableArray *animals;
@property (nonatomic, retain) NSArray *countArray;

-(void)checkAndCreateDatabase;
-(void)readAnimalsFromDatabase;

-(void) checking;
@end


sqliteAppDelegate.m

#import "SQLiteTutorialAppDelegate.h"
#import "RootViewController.h"
#import "Animal.h" // Import the animal object header

@implementation SQLiteTutorialAppDelegate

@synthesize window;
@synthesize tabController;
@synthesize animals, countArray; // Synthesize the aminals array



- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Setup some globals
databaseName = @"Tips.sqlite";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
// Execute the "checkAndCreateDatabase" function
[self checkAndCreateDatabase];
// Query the database for all animal records and construct the "animals" array
[self readAnimalsFromDatabase];
[self checking];
// Configure and show the window
[window addSubview:[tabController view]];
[window makeKeyAndVisible];
}

- (void)applicationWillTerminate:(UIApplication *)application {
// Save data if appropriate
}

- (void)dealloc {
[animals release];
[tabController release];
[window release];
[super dealloc];
}

-(void) checkAndCreateDatabase{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];
// If the database already exists then return without doing anything
if(success) return;
// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
[fileManager release];
}

-(void) readAnimalsFromDatabase {
// Setup the database object
sqlite3 *database;
// Init the animals Array
NSMutableArray *animals2 = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select * from Tips_Cat";
        
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
                NSString *aNameCount = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
            // Create a new animal object with the data from the database
                int d= [aNameCount intValue];
                
Animal *animal = [[Animal alloc] initWithName:aName and :[NSNumber numberWithInteger:d]];
// Add the animal object to the animals Array
[animals2 addObject:animal];
                
[animal release];
            }
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
self.animals=animals2;
    [animals2 release];
}

-(void) checking
{
    sqlite3 *database;
    // Open the database from the users filessytem
    NSMutableArray *tempArray1 = [[NSMutableArray alloc]init];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select count(*) from Tips group by tip_cat_id";
        
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
               // sqlite3_col
int d;
                d=sqlite3_column_int(compiledStatement,0);
                //NSLog(@"count==%d",d);
                NSNumber *n1=[NSNumber numberWithInteger:d];
                [tempArray1 addObject:n1];
                //[tempArray1 addobject:[NSNumber numberWithInteger:d]];
                
                
                //NSLog(@"count==%d",countArray);
            }
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
    
    
sqlite3_close(database);
self.countArray = tempArray1;
    [tempArray1 release];
}

@end


Database





RootViewController.h


#import <UIKit/UIKit.h>
#import "AnimalViewController.h"
#import "textController.h"
#import "favoriteController.h"
#import "CustomCell.h"
#import <sqlite3.h> 

@interface RootViewController : UITableViewController {
AnimalViewController *animalView;
    NSString *databaseName1;
NSString *databasePath1;
    NSMutableArray *sampleArray;
    int totCountView;
    IBOutlet UIImageView *navBarImage;
    IBOutlet UIImageView *bgImage;
    IBOutlet UIImageView *back1Image;
    IBOutlet UIImageView *back2Image;
 }

@property(nonatomic, retain) AnimalViewController *animalView; 
@property(nonatomic,retain)NSMutableArray *sampleArray;
-(NSMutableArray *) readAnimalsFromDatabase:(int)z;
@property int totCountView;
@property(nonatomic, retain)IBOutlet UIImageView *navBarImage;
@property(nonatomic, retain)IBOutlet UIImageView *bgImage;
@property(nonatomic, retain)IBOutlet UIImageView *back1Image;
@property(nonatomic, retain)IBOutlet UIImageView *back2Image;
@end


RootViewController.m


#import "RootViewController.h"
#import "SQLiteTutorialAppDelegate.h"
#import "AnimalViewController.h"
#import "textController.h"
#import "Animal.h"

@implementation RootViewController

@synthesize animalView, sampleArray, totCountView, navBarImage, bgImage, back1Image, back2Image;

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    SQLiteTutorialAppDelegate *appDelegate = (SQLiteTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
     totCountView = appDelegate.animals.count;
return appDelegate.animals.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 61;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    SQLiteTutorialAppDelegate *appDelegate = (SQLiteTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
Animal *animal = (Animal *)[appDelegate.animals objectAtIndex:indexPath.row];
    
    NSString *displayText=[NSString stringWithFormat:@"%@ (%d)",animal.name,[[appDelegate.countArray objectAtIndex:indexPath.row]intValue]];
    CustomCell *cellDisp = [[CustomCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil title:displayText and:indexPath.row];
    cellDisp.backgroundColor=[UIColor clearColor];
    return cellDisp;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SQLiteTutorialAppDelegate *appDelegate = (SQLiteTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
Animal *animal = (Animal *)[appDelegate.animals objectAtIndex:indexPath.row];
  
    AnimalViewController *viewController = [[AnimalViewController alloc] initWithNibName:@"AnimalViewController" bundle:nil];
    viewController.accessArray= [self readAnimalsFromDatabase:indexPath.row+1];
    viewController.printTitle = animal.name;
        
    viewController.totalCount = [[appDelegate.countArray objectAtIndex:indexPath.row]intValue];
       
    [self.navigationController pushViewController:viewController animated:YES];
    [viewController release];
}


- (void)viewDidLoad
  {
    databaseName1=@"Tips.sqlite";
    self.view.backgroundColor = [UIColor clearColor];
   // self.title = @"Quotes List";
    [self.navigationController setNavigationBarHidden:YES];
      
      navBarImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"topbg.png"]];
      [self.navigationController.view addSubview:navBarImage];  
      self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); 

      UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"Bg.png"]];
      self.view.backgroundColor = background;
      [background release];
      
      UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(60, 28, 200, 20)];
      label.backgroundColor = [UIColor clearColor];
      label.font = [UIFont boldSystemFontOfSize:20.0];
      label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
      label.textAlignment = UITextAlignmentCenter;
      label.textColor = [UIColor whiteColor];
      self.navigationItem.titleView = label;
      label.text = @"Quote Book";
      [self.navigationController.view addSubview:label]; 
      [label release];
      
    [super viewDidLoad];
  }

-(NSMutableArray *) readAnimalsFromDatabase:(int)z
{
// Setup the database object
sqlite3 *database;
    NSMutableArray *mutableArray = [[NSMutableArray alloc ]init];
// Init the animals Array
NSArray *myArrayName = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [myArrayName objectAtIndex:0];
databasePath1 = [documentsDir stringByAppendingPathComponent:databaseName1];
// Open the database from the users filessytem
if(sqlite3_open([databasePath1 UTF8String], &database) == SQLITE_OK) {
        NSString *stringName = [NSString stringWithFormat:@"SELECT tip_text FROM Tips where tip_cat_id=%d",z];        
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = [stringName UTF8String];
        sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aName1 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
            [mutableArray addObject:aName1];
}
}
// Release the compiled statement from memory  
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
self.sampleArray=mutableArray;
[mutableArray release];
return self.sampleArray;
}

/*
// Override to support editing the list
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support conditional editing of the list
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support rearranging the list
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the list
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}s
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
}
*/

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
[animalView release];
[sampleArray release];
    [super dealloc];
}


@end




CustomCell.h

//
//  CustomCell.h
//  SQLiteTutorial
//
//  Created by AEL DATA on 22/11/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface CustomCell : UITableViewCell{

}


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier title:(NSString*)title and:(int)index;

@end


CustomCell.m

//
//  CustomCell.m
//  SQLiteTutorial
//
//  Created by AEL DATA on 22/11/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CustomCell.h"

@implementation CustomCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier title:(NSString*)title and:(int)index{
   
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self!=nil){
        UIImageView *image =[[UIImageView alloc]initWithFrame:CGRectMake(0,0,320,61)];
        UIImage *setImage = (index%2==0)?[UIImage imageNamed:@"tile1.png"]:[UIImage imageNamed:@"tile2.png"];
        image.image = setImage;
        [self addSubview:image];
        [image release];
        
        UILabel *imagelabel = [[UILabel alloc]initWithFrame:CGRectMake(0,0,self.frame.size.width,50)];
        imagelabel.backgroundColor=[UIColor clearColor];
        imagelabel.text = title;
        [self addSubview:imagelabel];
        [imagelabel release];
    }
    return self;
}

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

    // Configure the view for the selected state
}

@end



Animal.h

#import <UIKit/UIKit.h>

@interface Animal : NSObject {
NSString *name;
    NSNumber *nameCount;
}

@property (nonatomic, retain) NSString *name;

@property(nonatomic, retain) NSNumber *nameCount;


-(id)initWithName:(NSString *)n and :(NSNumber *)a;


@end


Animal.m

#import "Animal.h"

@implementation Animal
@synthesize name;
@synthesize nameCount;

-(id)initWithName:(NSString *)n and :(NSNumber *)a{
self.name = n;
    self.nameCount = a;
return self;
}
-(void)dealloc
{
    [super dealloc];
    [name release];
    [nameCount release];
}
@end


AnimalViewController.h

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

@interface AnimalViewController : UIViewController {
IBOutlet UITableView *Desciption;
    NSMutableArray *accessArray;
    NSString *printTitle;
    
    int totalCount;
    
}

@property (nonatomic, retain) IBOutlet UITableView *Desciption;

@property(nonatomic,retain) NSMutableArray *accessArray;

@property(nonatomic,retain) NSString *printTitle;

@property int totalCount;



@end

AnimalViewController.m


#import "AnimalViewController.h"
#import "textController.h"


@implementation AnimalViewController

@synthesize Desciption;

@synthesize accessArray, printTitle, totalCount;
/*
// Override initWithNibName:bundle: to load the view using a nib file then perform additional customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/ 

/*
// Implement loadView to create a view hierarchy programmatically.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad
{
   // self.title = printTitle;
    
    UIImageView *back1Image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"back1.png"]];
    [self.navigationController.view addSubview:back1Image];  
    self.view.frame = CGRectMake(300, 300, self.view.frame.size.width, self.view.frame.size.height); 
    [back1Image release];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(60, 28, 200, 20)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:20.0];
    label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = label;
    label.text = printTitle;
    [self.navigationController.view addSubview:label]; 
    [label release];
    
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"Bg.png"]];
    self.view.backgroundColor = background;
    [background release];

    [super viewDidLoad];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    textController *viewController = [[textController alloc] initWithNibName:@"textController" bundle:nil];
    viewController.printState= [accessArray objectAtIndex:indexPath.row];
    viewController.printArray= accessArray;
    viewController.count = indexPath.row
    
    viewController.totalCount1 = totalCount;
    
    [self.navigationController pushViewController:viewController animated:YES];
    [viewController release];
   
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
    [super dealloc];
[Desciption release];
[accessArray release];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 61;
}

    
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [accessArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   /* static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    } */
    NSString *displayText = [accessArray objectAtIndex:indexPath.row];
    CustomCell *cellDisp = [[CustomCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil title:displayText and:indexPath.row];
    cellDisp.backgroundColor=[UIColor clearColor];
return cellDisp;
}





@end


textViewController.h

//
//  textController.h
//  SQLiteTutorial
//
//  Created by AEL DATA on 01/11/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <sqlite3.h>
#import <MessageUI/MFMessageComposeViewController.h>
#import <MessageUI/MFMailComposeViewController.h>


@interface textController : UIViewController <UIAlertViewDelegate>
{
    NSString *printState;
    IBOutlet UITextView *textView;
    IBOutlet UITextField *textCountView;
    NSArray *textArray;
    NSString *txtCntrlr;
    NSArray *printArray;
    NSString *tCount;
    
    int totalCount1;
    int count;
    
    IBOutlet UIButton *smsBtn;
    IBOutlet UIButton *mailBtn;
    IBOutlet UIButton *favBtn;
    IBOutlet UIButton *remvefavBtn;
    
}

@property (nonatomic, retain) NSString *printState;
@property(nonatomic, retain)IBOutlet UITextView *textView;
@property(nonatomic, retain)IBOutlet UITextField *textCountView;
@property(nonatomic, retain)NSArray *textArray;
@property(nonatomic, retain)NSString *txtCntrlr;
@property (nonatomic, retain) NSArray *printArray;
@property(nonatomic, retain) IBOutlet UIButton *smsBtn;
@property(nonatomic, retain) IBOutlet UIButton *mailBtn;
@property(nonatomic, retain) IBOutlet UIButton *favBtn;
@property(nonatomic, retain) NSString *tCount;
@property(nonatomic, retain)IBOutlet UIButton *remvefavBtn;

@property int totalCount1;
@property int count;

- (IBAction)smsbuttonPressed:(id)sender;
- (IBAction)mailbuttonPressed:(id)sender;
- (IBAction)favbuttonPressed:(id)sender;
-(IBAction)remvefavBtnPressed:(id)sender;

-(void)displayComposerSheet;
-(void)launchMailAppOnDevice;

@end


textViewController.m

//
//  textController.m
//  SQLiteTutorial
//
//  Created by AEL DATA on 01/11/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "textController.h"
#import "favoriteController.h"

@implementation textController

@synthesize printState;

@synthesize textView, textCountView, textArray, txtCntrlr, printArray, count, smsBtn, mailBtn, favBtn, totalCount1, tCount;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        // Custom initialization
    }
    return self;
}
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    textView.textprintState;
    
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"Bg.png"]];
    self.view.backgroundColor = background;
    [background release];
    
    NSString *countStr  = [[NSNumber numberWithInt:count+1] stringValue];
    
    NSString *totCountStr  = [[NSNumber numberWithInt:totalCount1] stringValue];
    tCount = [[NSString alloc]initWithString:totCountStr];
    
    textCountView.text =[NSString stringWithFormat:@"%@ / %@",countStr,tCount];
    
    // -----------------------------
// One finger, swipe Left
// -----------------------------
    
    UISwipeGestureRecognizer *oneFingerSwipeUp =
  [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerSwipeUp:)] autorelease];
    [oneFingerSwipeUp setDirection:UISwipeGestureRecognizerDirectionLeft];
    [[self view] addGestureRecognizer:oneFingerSwipeUp];
    
// -----------------------------
// One finger, swipe Right
// -----------------------------
    UISwipeGestureRecognizer *oneFingerSwipeDown =
  [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerSwipeDown:)] autorelease];
    [oneFingerSwipeDown setDirection:UISwipeGestureRecognizerDirectionRight];
    
    [[self view] addGestureRecognizer:oneFingerSwipeDown];
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)oneFingerSwipeUp:(UISwipeGestureRecognizer *)recognizer
{
    if(count<[printArray count]-1)
    {
        count++;
        NSString *countStr  = [[NSNumber numberWithInt:count+1] stringValue];
        textCountView.text =[NSString stringWithFormat:@"%@ / %@",countStr,tCount];

         //[self fadeInFromFadeOut:textView withDuration:2]; 
        textView.text= [printArray objectAtIndex:count];
    }
    
    //CGPoint point = [recognizer locationInView:[self view]];
   // NSLog(@"Swipe up - start location: %f,%f", point.x, point.y);
}

- (void)oneFingerSwipeDown:(UISwipeGestureRecognizer *)recognizer
{
    if(count>=1)
    {
        NSString *countStr  = [[NSNumber numberWithInt:count] stringValue];
        textCountView.text =[NSString stringWithFormat:@"%@ / %@",countStr,tCount];
        count--;
        //[self fadeInFromFadeOut:textView withDuration:2];
        textView.text= [printArray objectAtIndex:count];
    }
    
    //CGPoint point = [recognizer locationInView:[self view]];
    //NSLog(@"Swipe down - start location: %f,%f", point.x, point.y);
}

-(void)fadeOut:(UIView*)viewToDissolve withDuration:(NSTimeInterval)duration   andWait:(NSTimeInterval)wait
{
[UIView beginAnimations: @"Fade Out" context:nil];
// wait for time before begin
[UIView setAnimationDelay:wait];
// duration of animation
[UIView setAnimationDuration:duration];
viewToDissolve.alpha = 0.0;
[UIView commitAnimations];
}

-(void)fadeIn:(UIView*)viewToFadeIn withDuration:(NSTimeInterval)duration   andWait:(NSTimeInterval)wait
{
[UIView beginAnimations: @"Fade In" context:nil];
// wait for time before begin
[UIView setAnimationDelay:wait];
    
    // druation of animation
[UIView setAnimationDuration:duration];
viewToFadeIn.alpha = 1;
[UIView commitAnimations];
}


-(void) fadeInFromFadeOut: (UIView*)viewToFadeIn withDuration:(NSTimeInterval)duration
{
viewToFadeIn.hidden=NO;
[self fadeOut:viewToFadeIn withDuration:1 andWait:0.2];
[self fadeIn:viewToFadeIn withDuration:duration andWait:0.2];
}




- (IBAction)favbuttonPressed:(id)sender
{
NSArray *documentDirectory=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentPath=[documentDirectory objectAtIndex:0];
    NSString *plistPath = [documentPath stringByAppendingPathComponent:@"favourite.plist"];
NSFileManager *fileManager=[NSFileManager defaultManager];
//[[NSMutableArray alloc]init];
    if ([fileManager fileExistsAtPath:plistPath])
{
NSMutableArray *plistArray= [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
[plistArray addObject:textView.text];
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistArray
 
  format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
[plistData writeToFile:plistPath atomically:YES];
[plistArray release];
}
else {
NSMutableArray *plistArray=[[NSMutableArray alloc]init];
        [plistArray addObject:textView.text];
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistArray
 
  format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
[plistData writeToFile:plistPath atomically:YES];
[plistArray release];
}
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Added" message:@"Quote has been added to favourite!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:/*@"CANCEL",*/ nil]; 
    [alert show];
    [alert release];
}

-(IBAction)remvefavBtnPressed:(id)sender
{


}


- (IBAction)smsbuttonPressed:(id)sender
{
    [self sendSMS:textView.text recipientList:[NSArray arrayWithObjects:@"", @"", nil]];
}


- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
[self dismissModalViewControllerAnimated:YES];
    
    if (result == MessageComposeResultCancelled)
    {
        //NSLog(@"Message cancelled");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Message cancelled!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:/*@"CANCEL",*/ nil]; 
        [alert show];
        [alert release];
    }
        
    else if (result == MessageComposeResultSent)
    {
        //NSLog(@"Message sent");  
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Message sent!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:/*@"CANCEL",*/ nil]; 
        [alert show];
        [alert release];
    }
        else
        {
           //NSLog(@"Message failed");  
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Message failed!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:/*@"CANCEL",*/ nil]; 
            [alert show];
            [alert release];
        }
}


- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
    if([MFMessageComposeViewController canSendText])
    {
        controller.body = bodyOfMessage;  
        controller.recipients = recipients;
        controller.messageComposeDelegate = self;
        [self presentModalViewController:controller animated:YES];
    }  
}


- (IBAction)mailbuttonPressed:(id)sender
{
    // This sample can run on devices running iPhone OS 2.0 or later  
// The MFMailComposeViewController class is only available in iPhone OS 3.0 or later. 
// So, we must verify the existence of the above class and provide a workaround for devices running 
// earlier versions of the iPhone OS. 
// We display an email composition interface if MFMailComposeViewController exists and the device can send emails.
// We launch the Mail application on the device, otherwise.
Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
if (mailClass != nil)
{
// We must always check whether the current device is configured for sending emails
if ([mailClass canSendMail])
{
[self displayComposerSheet];
}
else
{
[self launchMailAppOnDevice];
}
}
else
{
[self launchMailAppOnDevice];
}
}

// Displays an email composition interface inside the application. Populates all the Mail fields. 
-(void)displayComposerSheet
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:@""];
    
// Set up recipients
NSArray *toRecipients = [[NSArray alloc]init];
NSArray *ccRecipients = [[NSArray alloc]init];
NSArray *bccRecipients = [[NSArray alloc]init];
[picker setToRecipients:toRecipients];
[picker setCcRecipients:ccRecipients];
[picker setBccRecipients:bccRecipients];
// Fill out the email body text
NSString *emailBody = textView.text;
[picker setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
    [picker release];
}

// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
// Notifies users about errors associated with the interface
switch (result)
{
case MFMailComposeResultCancelled:
//message.text = @"Result: canceled";
            ;
            UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"Email" message:@"Cancelled!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:/*@"CANCEL",*/ nil]; 
            [alert1 show];
            [alert1 release];
break;
case MFMailComposeResultSaved:
//message.text = @"Result: saved";
            ;
            UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:@"Email" message:@"Saved!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:/*@"CANCEL",*/ nil]; 
            [alert2 show];
            [alert2 release];
break;
case MFMailComposeResultSent:
//message.text = @"Result: sent";
            ;
            UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:@"Email" message:@"Sent!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:/*@"CANCEL",*/ nil]; 
            [alert3 show];
            [alert3 release];
break;
case MFMailComposeResultFailed:
//message.text = @"Result: failed";
            ;
            UIAlertView *alert4 = [[UIAlertView alloc] initWithTitle:@"Email" message:@"Failed!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:/*@"CANCEL",*/ nil]; 
            [alert4 show];
            [alert4 release];
break;
default:
//message.text = @"Result: not sent";
            ;
            UIAlertView *alert5 = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Not sent!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:/*@"CANCEL",*/ nil]; 
            [alert5 show];
            [alert5 release];
break;
}
[self dismissModalViewControllerAnimated:YES];
}


#pragma mark -
#pragma mark Workaround

// Launches the Mail application on the device.
-(void)launchMailAppOnDevice
{
NSString *recipients = @"";
NSString *body = @"";
NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end


favoriteView.h

//
//  favoriteController.h
//  SQLiteTutorial
//
//  Created by AEL DATA on 08/11/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>


@interface favoriteController : UIViewController
{
    NSString *favState;
    NSMutableArray *favArray;
    
    IBOutlet UITableView *atableview;
    IBOutlet UIImageView *navBarImage;
    
}
@property (nonatomic, retain) NSString *favState;
@property (nonatomic, retain) NSArray *favArray;
@property (nonatomic, retain) IBOutlet UITableView *atableview;
@property (nonatomic, retain) IBOutlet UIImageView *navBarImage;
@end


favorite.m

//
//  favoriteController.m
//  SQLiteTutorial
//
//  Created by AEL DATA on 08/11/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "favoriteController.h"
#import "fView.h"

@implementation favoriteController

@synthesize favArray, favState, atableview, navBarImage;

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

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
-(void)viewWillAppear:(BOOL)animated
{
        [super viewWillAppear:YES];

}
-(void)viewDidAppear:(BOOL)animated
{
    NSArray *documentDirectory=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentPath=[documentDirectory objectAtIndex:0];
    NSString *plistPath = [documentPath stringByAppendingPathComponent:@"favourite.plist"];
favArray= [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
    [atableview reloadData];
    [super viewDidAppear:YES];
}
- (void)viewDidLoad
{
    self.title = @"Favorites";
    
    [self.navigationController setNavigationBarHidden:YES];
    
    navBarImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"topbg.png"]];
    [self.navigationController.view addSubview:navBarImage];  

    
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"Bg.png"]];
    self.view.backgroundColor = background;
    [background release];
    
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [favArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    
    
    cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"page_8.png"]];
    
    cell.textLabel.text = [favArray objectAtIndex:indexPath.row];
     
    return cell;
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)tableView:(UITableView *)tableview didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{  
    fView*new = [[fView alloc]initWithNibName:@"fView" bundle:[NSBundle mainBundle]];
    new.dispStr= [favArray objectAtIndex:indexPath.row];
    new.dispArr= favArray;
    new.countInt = indexPath.row;
    
    [self.navigationController pushViewController:new animated:YES];
    [new release];
}


@end


fView.h

//
//  fView.h
//  SQLiteTutorial
//
//  Created by AEL DATA on 11/11/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface fView : UIViewController
{
    IBOutlet UITextView *txtView;
    NSString *dispStr;
    NSArray *dispArr;
    int countInt;
    NSString *totFavCount;
    
    NSString *favCount;
    NSString *totFCount;
    NSString *tCounts;
    
    IBOutlet UITextField *textFeild;
}

@property(nonatomic, retain)IBOutlet UITextView *txtView;

@property(nonatomic, retain)NSString *dispStr;

@property(nonatomic, retain)NSArray *dispArr;

@property(nonatomic, retain)NSString *totFavCount;

@property(nonatomic, retain)NSString *favCount;

@property(nonatomic, retain)NSString *totFCount;

@property(nonatomic, retain) IBOutlet UITextField *textFeild;

@property(nonatomic, retain) NSString *tCounts;

@property int countInt;
@end


fView.m

//
//  fView.m
//  SQLiteTutorial
//
//  Created by AEL DATA on 11/11/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "fView.h"

@implementation fView

@synthesize txtView, dispStr, dispArr, countInt, totFavCount, favCount, totFCount, textFeild, tCounts;

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

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    txtView.textdispStr;
    self.title = @"Favorites";
    
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"Bg.png"]];
    self.view.backgroundColor = background;
    [background release];

    
    int totalCounts = [dispArr count];
    
    NSString *countStrg  = [[NSNumber numberWithInt:countInt+1] stringValue];
    
    NSString *totCountStrg  = [[NSNumber numberWithInt:totalCounts] stringValue];
    tCounts = [[NSString alloc]initWithString:totCountStrg];
    
    textFeild.text =[NSString stringWithFormat:@"%@ / %@",countStrg,tCounts];
    
    // -----------------------------
// One finger, swipe Left
// -----------------------------
    
    UISwipeGestureRecognizer *oneFingerSwipeUp =
  [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerSwipeUp:)] autorelease];
    [oneFingerSwipeUp setDirection:UISwipeGestureRecognizerDirectionLeft];
    [[self view] addGestureRecognizer:oneFingerSwipeUp];
    
// -----------------------------
// One finger, swipe Right
// -----------------------------
    UISwipeGestureRecognizer *oneFingerSwipeDown =
  [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerSwipeDown:)] autorelease];
    [oneFingerSwipeDown setDirection:UISwipeGestureRecognizerDirectionRight];
    
    [[self view] addGestureRecognizer:oneFingerSwipeDown];
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)oneFingerSwipeUp:(UISwipeGestureRecognizer *)recognizer
{
    if(countInt<[dispArr count]-1)
    {
        countInt++;
        NSString *countStrg  = [[NSNumber numberWithInt:countInt+1] stringValue];
        textFeild.text =[NSString stringWithFormat:@"%@ / %@",countStrg,tCounts];
        
        //[self fadeInFromFadeOut:textView withDuration:2]; 
        txtView.text= [dispArr objectAtIndex:countInt];
    }
    
    //CGPoint point = [recognizer locationInView:[self view]];
    //NSLog(@"Swipe up - start location: %f,%f", point.x, point.y);
}

- (void)oneFingerSwipeDown:(UISwipeGestureRecognizer *)recognizer
{
    if(countInt>=1)
    {
        NSString *countStrg  = [[NSNumber numberWithInt:countInt] stringValue];
        textFeild.text =[NSString stringWithFormat:@"%@ / %@",countStrg,tCounts];

        countInt--;
        //[self fadeInFromFadeOut:textView withDuration:2];
        txtView.text= [dispArr objectAtIndex:countInt];
    }
    
    //CGPoint point = [recognizer locationInView:[self view]];
    //NSLog(@"Swipe down - start location: %f,%f", point.x, point.y);
}

-(void)fadeOut:(UIView*)viewToDissolve withDuration:(NSTimeInterval)duration   andWait:(NSTimeInterval)wait
{
[UIView beginAnimations: @"Fade Out" context:nil];
// wait for time before begin 
[UIView setAnimationDelay:wait];
// duration of animation
[UIView setAnimationDuration:duration];
viewToDissolve.alpha = 0.0;
[UIView commitAnimations];
}

-(void)fadeIn:(UIView*)viewToFadeIn withDuration:(NSTimeInterval)duration   andWait:(NSTimeInterval)wait
{
[UIView beginAnimations: @"Fade In" context:nil];
// wait for time before begin
[UIView setAnimationDelay:wait];
    
    // druation of animation
[UIView setAnimationDuration:duration];
viewToFadeIn.alpha = 1;
[UIView commitAnimations];
}


-(void) fadeInFromFadeOut: (UIView*)viewToFadeIn withDuration:(NSTimeInterval)duration
{
viewToFadeIn.hidden=NO;
[self fadeOut:viewToFadeIn withDuration:1 andWait:0.2];
[self fadeIn:viewToFadeIn withDuration:duration andWait:0.2];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end





No comments:

Post a Comment