Friday, 25 September 2015

Sqlite CASE expression

A CASE expression serves a role similar to IF-THEN-ELSE in other programming languages.
The optional expression that occurs in between the CASE keyword and the first WHEN keyword is called the "base" expression. There are two basic forms of the CASE expression: those with a base expression and those without.

In a CASE without a base expression, each WHEN expression is evaluated and the result treated as a boolean, starting with the leftmost and continuing to the right. The result of the CASE expression is the evaluation of the THEN expression that corresponds to the first WHEN expression that evaluates to true. Or, if none of the WHEN expressions evaluate to true, the result of evaluating the ELSE expression, if any. If there is no ELSE expression and none of the WHEN expressions are true, then the overall result is NULL.
A NULL result is considered untrue when evaluating WHEN terms.


For example, we consider a table 'Employee' with column 'Emp_id', 'Emp_name','Emp_DOB','Emp_Department'.
Assume, we already have some data on table.
So the task is to interchange  'Emp_Department'
Suppose only two department is Marketing and Production and we want to change Marketing employee to Production and Production to employee.
We can use two separate Update query statement for completion of above task.
But i am going to use CASE EXPRESSION.

Here simple query for interchange Emp_Department.
Update Employee set Emp_Department = case when Emp_Department = 'Marketing' then 'Production' else 'Marketing' end

Code
-(NSString *) getUserDBPath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
  
    NSString *documentsDir = [paths objectAtIndex:0];
    return [documentsDir stringByAppendingPathComponent:@"Employee.sqlite"];
}


-(void) updateTableDetails{
    //Get Database path
    NSString *userDBPath = [self getUserDBPath];
    sqlite3 *userDatabase;

   //Open Database
    if (sqlite3_open([userDBPath UTF8String], &userDatabase) != SQLITE_OK){
        NSLog(@"Error to open user DB = %s",sqlite3_errmsg(userDatabase));
        userDatabase = nil;
    }
    sqlite3_stmt *queryStmt;

    //Update query for Update
    NSString *query = @"Update Employee set Emp_Department = case when Emp_Department = 'Marketing' then 'Production' else 'Marketing' end";

   //Prepare Statement
    if (sqlite3_prepare_v2(userDatabase, query.UTF8String, -1, &queryStmt, NULL) != SQLITE_OK) {
        NSLog(@"Error to prepare stmt=%s",sqlite3_errmsg(userDatabase));
        sqlite3_finalize(queryStmt);
        sqlite3_close(userDatabase);
        queryStmt = nil;
        userDatabase = nil;
    }
    if (sqlite3_step(queryStmt) == SQLITE_DONE) {
        NSLog(@"success");
    }
    else{
        NSLog(@"Error to step stmt = %s",sqlite3_errmsg(userDatabase));
    }
    sqlite3_finalize(queryStmt);
    sqlite3_close(userDatabase);
    queryStmt = nil;
    userDatabase = nil;
}



For More Detail Click Here

Friday, 18 September 2015

Display Table View Cell From Bottom

For the better user interface some time we need to display UITabelViewCell from bottom of the UITableView.
And, when we add new cell, its insert in bottom of UITableView and Table View auto scroll up for proper visualization for newly added cell.
We can use UITableView's contentInset for  this kind of behavior of UItableView.
Whenever add new cell update contentInset of Tableview.

Code
 -(void) updateTableViewInset:(UITableView *)tableView{
//First find out total number of cell in Table View
    NSInteger numRows=[tableView numberOfRowsInSection:0];

//Get height of Table View
    CGFloat contentInsetTop=tableView.bounds.size.height;
    for (int i=0;i<numRows;i++) {

//Get cell height and subtract by contentInsetTop
        contentInsetTop -= [self tableView:tableView heightForRowAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];

//Check if contentInsetTop reach to zero or less than zero
        if (contentInsetTop<=0) {
            contentInsetTop=0;
            break;
        }
    }

//update tableview contentInset.
    tableView.contentInset = UIEdgeInsetsMake(contentInsetTop, 0, 50, 0);
}

Friday, 11 September 2015

Animate UITextView With Text

//First set maximum height for UITextView
maximumHeight = 120;

//Add UITextView
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 50, 300, 40)];
    textView.delegate = self;
    textView.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:textView];


// Delegate of UItextView
-(void) textViewDidChange:(UITextView *)textView{

    UITextPosition* pos = textView.endOfDocument;//explore others like beginningOfDocument if you want to customize the behaviour
    CGRect currentRect = [textView caretRectForPosition:pos];

        CGRect  newFrame = textView.frame;
        newFrame.size.height = currentRect.size.height+currentRect.origin.y+5;
        if (newFrame.size.height>40 && newFrame.size.height<=maximumHeight) {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.1f];
            textView.frame = newFrame;
            [UIView commitAnimations];
        }
        else if (newFrame.size.height<40){
            newFrame.size.height=40;
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.1f];
            textView.frame = newFrame;
            [UIView commitAnimations];
        }
    }

Friday, 21 August 2015

Copy Table From One Database to another Database

SQLite is a powerful relational database used for storing data in iOS Applications.

Here code for, Copy table from one database to  another database.

-(void) createCopyDatabase{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    
 //Get path for Source Database
    NSString *maindbPath = [documentsDir stringByAppendingPathComponent:@"User.sqlite"];;
    
 //Path for new Database
    NSString *newdbPath = [documentsDir stringByAppendingPathComponent:@"User_copy.sqlite"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    char *error;

//Remove previously existing file
    if ([fileManager fileExistsAtPath:newdbPath]) {
        [fileManager removeItemAtPath:newdbPath error:nil];
    }
    sqlite3 *database;
    //open database
    if (sqlite3_open([newdbPath UTF8String], &database)!=SQLITE_OK) {
        NSLog(@"Error to open database");
    }
//Query for Attach both Database
    NSString *attachQuery = [NSString stringWithFormat:@"ATTACH DATABASE \"%@\" AS existingDB",maindbPath];
   
    sqlite3_exec(database, [attachQuery UTF8String], NULL, NULL, &error);
    if (error) {
        NSLog(@"Error to Attach = %s",error);
    }
//Query for copy Table
    NSString *sqlString = @"CREATE TABLE Info AS SELECT * FROM
existingDB.Info";     
    sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
    if (error) {
        NSLog(@"Error to copy database = %s",error);
    }
   
    //Query for copy Table with Where Clause
    sqlString = @"CREATE TABLE comments AS SELECT * FROM
existingDB.comments Where user_name = 'XYZ'";
    sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
    if (error) {
        NSLog(@"Error to copy database = %s",error); 
       
    }
   
}

Friday, 7 August 2015

Create Gradient Layer

The CAGradientLayer class draws a color gradient over its background color.
 Here code for create a gradient layer.
I am using white and red color for gradient colors.

//Create Gradient
    UIColor *firstColor = [UIColor whiteColor];
    UIColor *secColor = [UIColor redColor];
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.frame = self.view.bounds;
    firstColor = [UIColor whiteColor];
    NSNumber *f1 = [NSNumber numberWithFloat:0.0];
    NSNumber *f2 = [NSNumber numberWithFloat:1.0];
    layer.locations = [NSArray arrayWithObjects:f1,f2,f3,f4, nil];
    layer.colors = @[(id)firstColor.CGColor,(id)secColor.CGColor];




//Add Gradient to View
    [self.view.layer insertSublayer:layer atIndex:0];
//Add Shadow on Gradient
    layer.cornerRadius = 1.0f;
    layer.masksToBounds = NO;
    layer.shadowColor = [UIColor blackColor].CGColor;
    layer.shadowOpacity = 0.2;
    layer.shadowRadius = 2;
    layer.shadowOffset = CGSizeMake(0.0f, 1.0f);
    layer.shadowPath = [UIBezierPath bezierPathWithRect:layer.bounds].CGPath;

Friday, 24 July 2015

Image to Byte and Byte to Image conversion

In many situations we need to convert image to byte. It is useful in many scenarios because byte arrays can be easily compared, compressed, stored, or converted to other data types.
Here a simple code to convert image to byte array.

//Using image picker for select a image(we can use any specified way for selecting a image).

-(IBAction)openPhotoAlbum:(UIButton *)sender{
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    pickerController.delegate = self;
    [self presentViewController:pickerController animated:YES completion:nil];
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    // Get selected image
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self
convertImageToByte: image];
}
-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


//Convert image to byte format
-(void) convertImageToByte:(UIImage *)image{
       NSData *data = UIImagePNGRepresentation(image);
       NSUInteger len = data.length;
       uint8_t *bytes = (uint8_t *)[data bytes];
      NSMutableString *result = [NSMutableString stringWithCapacity:len * 3];
       for (NSUInteger i = 0; i < len; i++) {
        if (i) {
            [result appendString:@","];
        }
        [result appendFormat:@"%d", bytes[i]];
    }
    [result appendString:@"]"];
    NSLog(@"Image in Byte  = %@",result);

}  


//Change byte to UIImage
-(void)convierteImagen: (NSMutableString *)cadenaImagen{
   
    NSArray *strings = [cadenaImagen componentsSeparatedByString:@","];
    unsigned c = strings.count;
    uint8_t *bytes = malloc(sizeof(*bytes) * c);
   
    unsigned i;
    for (i = 0; i < c; i++)
    {
        NSString *str = [strings objectAtIndex:i];
        int byte = [str intValue];
        bytes[i] = (uint8_t)byte;
    }
   
    NSData *data = [NSData dataWithBytes:bytes length:c];

    //get image
    UIImage *image = [UIImage imageWithData:data];
    //Display image on UIImageView
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 400,   400)];
    imageView.image = image;
    [self.view addSubview:imageView];
}

Friday, 17 July 2015

Post Request in Swift

One of the very useful functionality and frequent used for mobile application development, if application interact with server.

Most of the application communicate with server over HTTP Post request.

In this blog you can see how to communicate with server over HTTP Post method.


 func postRequestToServer(postUrl:NSString, postParameters:NSDictionary) {     
        var url = NSURL(string: postUrl)
        var postData:NSData!
        postData = NSJSONSerialization.dataWithJSONObject(postParameters, options:                NSJSONWritingOptions.PrettyPrinted, error: nil)
       
        var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 50)
        var postDataLength = NSString(format: "%lu", postData.length)
       
        request.setValue(postDataLength, forHTTPHeaderField: "Content-Length")
        request.HTTPBody = postData
        request.HTTPMethod = "POST"
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        var urlResponse : NSURLResponse?
        var error : NSError?
        var responseData : NSData!
        responseData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &urlResponse, error: &error)
       
        var returnDict:NSDictionary? = nil
       
        if responseData==nil{
            println("Nil Response")
            return
        }
       
        var parseResponse: AnyObject? = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableLeaves, error: nil)
       
        if (parseResponse?.isKindOfClass(NSDictionary) != nil){
            NSLog("parse response = %@", parseResponse as NSDictionary)
        }
        else if ((parseResponse?.isKindOfClass(NSArray)) != nil){
            NSLog("parse response = %@", parseResponse as NSArray)
         }
       }//End method