Archive

Archive for the ‘Objective-C’ Category

Using Gesture

November 20, 2012 1 comment

 Today I tried to play with Gesture. There are 6 gestures that we can use in IPhone. They are Tap, Pinch, Rotate, Pan, Swipe, and Press. First thing todo is creating IOS Application with XCode (I use XCode 4.4.1), choose Single View Apps. Add 3 image files (IMG_0011.JPG, IMG_0082.JPG, IMG_0093.JPG) in the project.
As usual you have to write code in the ViewController.h and implementation file ViewController.m
Here is ViewController.h. You Need to add UIImageView with interface builder, then link it to imageView variable.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    IBOutlet UIImageView *imageView;
}

@property (nonatomic,retain) UIImageView *imageView;

-(IBAction)handleTapGesture:(UIGestureRecognizer *)sender;
-(IBAction)handlePinchGesture:(UIGestureRecognizer *)sender;
-(IBAction)handleRotateGesture:(UIGestureRecognizer *)sender;
-(IBAction)handlePanGesture:(UIGestureRecognizer *)sender;
-(IBAction)handleSwipeGesture:(UIGestureRecognizer *)sender;
-(IBAction)handleLongPress:(UIGestureRecognizer *)sender;

@end

And then implement methods to handle the gestures:
1. Tap Gesture

-(IBAction)handleTapGesture:(UIGestureRecognizer *)sender
{
    if(sender.view.contentMode == UIViewContentModeScaleAspectFit)
    {
        sender.view.contentMode = UIViewContentModeCenter;
    }
    else
    {
        sender.view.contentMode = UIViewContentModeScaleAspectFit;
    }
}

2. Pinch Gesture

-(IBAction)handlePinchGesture:(UIGestureRecognizer *)sender
{
    CGFloat factor = [(UIPinchGestureRecognizer *) sender scale];
    if(factor >1)
    {
        sender.view.transform = CGAffineTransformMakeScale(lastScaleFactor + (factor-1), lastScaleFactor + (factor-1));
    }
    else
    {
        sender.view.transform = CGAffineTransformMakeScale(lastScaleFactor*factor, lastScaleFactor*factor);
    }

    if(sender.state == UIGestureRecognizerStateEnded)
    {
        if(factor > 1)
            lastScaleFactor += (factor-1);
        else
            lastScaleFactor *= factor;
    }
}

3. Rotate Gesture

-(IBAction)handleRotateGesture:(UIGestureRecognizer *)sender
{
    CGFloat rotation = [(UIRotationGestureRecognizer *) sender rotation];
    sender.view.transform = CGAffineTransformMakeRotation(rotation + netRotation);
    if(sender.state == UIGestureRecognizerStateEnded)
    {
        netRotation += rotation;
    }
}

4. Pan/Drag Gesture

-(IBAction)handlePanGesture:(UIGestureRecognizer *)sender
{
    CGPoint translation = [(UIPanGestureRecognizer *) sender translationInView:imageView];
    sender.view.transform = CGAffineTransformMakeTranslation(netTranslation.x + translation.x, netTranslation.y + translation.y);

    if(sender.state == UIGestureRecognizerStateEnded)
    {
        netTranslation.x += translation.x;
        netTranslation.y += translation.y;
    }
}

5. Swipe Gesture

-(IBAction)handleSwipeGesture:(UIGestureRecognizer *)sender
{
    UISwipeGestureRecognizerDirection direction = [(UISwipeGestureRecognizer *) sender direction];
    switch (direction) {
        case UISwipeGestureRecognizerDirectionUp:
            NSLog(@"UP");
            break;
        case UISwipeGestureRecognizerDirectionDown:
            NSLog(@"DOWN");
        case UISwipeGestureRecognizerDirectionRight:
            imageIndex++;
            break;
        case UISwipeGestureRecognizerDirectionLeft:
            imageIndex--;
            break;
        default:
            break;
    }

    imageIndex = (imageIndex < 0) ? ([images count] - 1): imageIndex%[images count];
    imageView.image = [UIImage imageNamed:[images objectAtIndex:imageIndex]];
}

6. Press Gesture

-(IBAction)handleLongPress:(UIGestureRecognizer *)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Image Options"
                                                             delegate:self
                                                    cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"Save Image", @"Copy Image", nil];
    [actionSheet showInView:self.view];
}

Then Test it, by adding somecode in the viewDidLoad method

- (void)viewDidLoad
{

    // Tap Gesture
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                 action:@selector(handleTapGesture:)];
    tapGesture.numberOfTapsRequired = 2;
    [imageView addGestureRecognizer:tapGesture];

    // Pinch Gesture
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self
                                                                                       action:@selector(handlePinchGesture:)];
    [imageView addGestureRecognizer:pinchGesture];

    //Rotate Gesture
    UIRotationGestureRecognizer *rotateGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self
                                                                                              action:@selector(handleRotateGesture:)];
    [imageView addGestureRecognizer:rotateGesture];

    // Panning Gesture
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    [imageView addGestureRecognizer:panGesture];

    // Swipping
    images = [[NSArray alloc] initWithObjects:@"IMG_0011.JPG",@"IMG_0082.JPG",@"IMG_0093.JPG", nil];
    UISwipeGestureRecognizer *rightSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self
                                                                                     action:@selector(handleSwipeGesture:)];
    [imageView addGestureRecognizer:rightSwipeGesture];

    UISwipeGestureRecognizer *leftSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self
                                                                                    action:@selector(handleSwipeGesture:)];
    leftSwipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [imageView addGestureRecognizer:leftSwipeGesture];

    // LongPress Gesture
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    longPressGesture.minimumPressDuration = 1;
    longPressGesture.numberOfTouchesRequired = 1;
    longPressGesture.allowableMovement = 15;
    [imageView addGestureRecognizer:longPressGesture];

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
Advertisements
Categories: Objective-C

Accessing SQLite3 database in Objective-C

November 19, 2012 1 comment

Today I will show you how to access sqlite3 database with objective-C. I use XCode 4.4.1. First thing todo is to add sqlite3 library (libsqlite3.dylib) to  framework directory in your project.

Then write the interface file ViewController.h:

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

@interface ViewController : UIViewController
{
  sqlite3 *db;
}

-(NSString *) filePath;
-(void) openDB;
-(void) createTableNamed:(NSString *) tableName
withField1:(NSString *) field1
withField2:(NSString *) field2;

-(void) insertRecordIntoTableNamed:(NSString *) tableName
withField1:(NSString *) field1
field1Value:(NSString *) field1Value
withField2:(NSString *) field2
field2Value:(NSString *) field2Value;

-(void) getAllRowsFromTableNamed:(NSString *)tableName;
@end

and then implement methods in ViewController.m:
1. filePath: this method returns the full path of the database that will be created in the Documents folder within apllication’s sandbox

-(NSString *) filePath
{

    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                           NSUserDomainMask,YES);
    NSString *documentDir = [path objectAtIndex:0];
    return [documentDir stringByAppendingPathComponent:@"database.sql"];

}

2. openDB: this method will open the database or create database if database is not exists

-(void) openDB
{
    if(sqlite3_open([[self filePath] UTF8String], &(db)) != SQLITE_OK)
    {
        sqlite3_close(db);
        NSAssert(0, @"Database failed to open");
    }
}

3. createTableNamed: this method will create table if table is not exists

-(void) createTableNamed:(NSString *) tableName
              withField1:(NSString *) field1
              withField2:(NSString *) field2
{
    char *err;
    NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' TEXT PRIMARY KEY,'%@' TEXT);", tableName, field1, field2 ];

    if(sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK )
    {
        sqlite3_close(db);
        NSAssert(0, @"Table failed to create");
    }

}

4. insertRecordIntoTableNamed: this method will insert or replace records

-(void) insertRecordIntoTableNamed:(NSString *)tableName withField1:(NSString *)field1 field1Value:(NSString *)field1Value withField2:(NSString *)field2 field2Value:(NSString *)field2Value
{
    char *err;
    NSString *sql = [NSString stringWithFormat:@"INSERT OR REPLACE INTO '%@' ('%@','%@') VALUES ('%@','%@') ; ", tableName, field1, field2, field1Value, field2Value ];
    if(sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK  )
    {   
        sqlite3_close(db);
        NSAssert(0, @"Error Inserting/Updating Table");
    }
}

5. getAllRowsFromTableNamed: this method will retrieves records

-(void) getAllRowsFromTableNamed:(NSString *)tableName
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@", tableName];
    sqlite3_stmt * statement;

    if(sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil) == SQLITE_OK)
    {
        while(sqlite3_step(statement) == SQLITE_ROW)
        {
            char *field1 = (char *) sqlite3_column_text(statement, 0);
            NSString *field1Str = [[NSString alloc] initWithUTF8String:field1];
            char *field2 = (char *) sqlite3_column_text(statement, 1);
            NSString *field2Str = [[NSString alloc] initWithUTF8String:field2];

            NSString *str = [[NSString alloc] initWithFormat:@"%@ - %@", field1Str, field2Str];

            NSLog(@"%@",str);
        }
    }
}

To test it, insert some code in viedDidLoad method:

-(void)viewDidLoad
{
    [self openDB];
    [self createTableNamed:@"Contacts"
                withField1:@"name"
                withField2:@"email"];

    for(int i=0; i<5; i++)
    {
        NSString *name = [[NSString alloc] initWithFormat:@"User%d", i];
        NSString *email = [[NSString alloc] initWithFormat:@"user%d@yahoo.com", i];

        [self insertRecordIntoTableNamed:@"Contacts"
                              withField1:@"name"
                             field1Value:name
                              withField2:@"email"
                             field2Value:email];
    }

    [self getAllRowsFromTableNamed:@"Contacts"];
    [super viewDidLoad];
}

The Output :

2012-11-19 19:59:15.549 Databases[4388:c07] User0 - user0@yahoo.com
2012-11-19 19:59:15.552 Databases[4388:c07] User1 - user1@yahoo.com
2012-11-19 19:59:15.552 Databases[4388:c07] User2 - user2@yahoo.com
2012-11-19 19:59:15.553 Databases[4388:c07] User3 - user3@yahoo.com
2012-11-19 19:59:15.553 Databases[4388:c07] User4 - user4@yahoo.com