Friday, 22 January 2016

Draw Custom View With Transparent Oval

UIBezierPath define a path consisting of straight and curved line segment and render the path in custom views. We can use this for specify the geometry of path, path can define simple shapes such as rectangle, oval, arc or can define complex polygons.For more details about UIBezierPath Click Here.

I am going to draw a custom view with transparent oval.I will use UIBenzierPath  fro achieving result.

First create a SubClass of UIView.
Ex. named sub class to CustomView
Inside drawRect: method of CustomView.m

- (void)drawRect:(CGRect)rect {
    // Drawing code

//First Create path for Oval
    UIBezierPath *apath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(5, 5,  self.frame.size.width-10, self.frame.size.height-10)];
    //Create another path
    UIBezierPath *clipPath = [ UIBezierPath bezierPathWithRect:CGRectInfinite];

//Append both path
    [clipPath appendPath:apath];
    clipPath.usesEvenOddFillRule = YES; //

usesEvenOddFillRule property is used to determine whether the even-odd or non-zero rule is used to determine the area enclosed by the path.   

  CGContextSaveGState(UIGraphicsGetCurrentContext());
    [clipPath addClip];
    CGContextSaveGState(UIGraphicsGetCurrentContext());
    [[UIColor orangeColor] setFill];
    [[UIColor blackColor] setStroke];
    clipPath.lineWidth = 2;
    [clipPath stroke];
    [clipPath fill];
}

Friday, 18 December 2015

Math functions in Objective C

Objective C uses c' s math functions which can find in "math.h".
Here, list of some functions which frequently use in code:

1) pow: power of
double pow(double, double)
Ex:  double value = pow (5, 2);   // value = 25
       double value = pow (2, 5);   // value = 32

2) sqrt : square root
double sqrt(double);
Ex: double value = sqrt(16);     // value = 4;

3) ceil : if argument have any decimal value return next integer value(as a double)
 double ceil(double);
Ex: double value = ceil(2.0320);    // value = 3;
      double value = ceil(2.000);    // value = 2;

4) floor :  discard decimal part of argument.
 double floor(double);
Ex: double value = floor(1.98989);    value = 1;

5) round : Round the argument. if a argument have decimal value greater than or equals to  0.5 than return next integer value, and if  decimal value less than 0.5 than return integer part.
 double round(double);
Ex: double value = round(4.5);   //value = 5;
      double value = round(4.4);   //value = 4;

6)fmin : return smallest argument.
   double fmin(double, double);
  Ex: double value = fmin(3, 6);      //value = 3;

7)fmax : return bigger argument.
 double fmax(double, double);
 Ex: double value = fmax(3, 6);     //value = 6;

8)fabs : return absolute value of argument.
 double fabs(double);
 Ex: double value = fabs(10);      // value = 10;
       double value = fabs(-10);      // value = 10;

For more details check ''math.h". 

Friday, 27 November 2015



CocoaPods is a way to manage library dependencies in Xcode Project.

Installation of  CocoaPods.

CocoaPods runs on Ruby and that's only dependency it has. All recent version of Mac OS X(Since OS X 10.7) ship with Ruby already installed. So only need to update RubyGems.

To Update RubyGems open Terminal and type following command:

sudo gem update --system                                                                

Enter password when requested.
This update may take little while, so give few times to complete.

Next, install CocoaPods using following command:

sudo gem install cocoapods                                                                

if get below prompt during installation process:
 rake's execute "rake" conflicts with /user/bin/rake
Overwrite the executable? [y/n]
just enter y to continue.

Now, type the command to complete the process of CocoaPods installation:
pod setup                                                                                               


Done, now we are ready to use CocoaPods.

 Installation of dependency within the Project using CocoaPods
use Terminal and navigate to Project directory

cd ~/.. /.. /Project Name

Now,  type following command to create Podfile for Project.
pod init

Type command to open Podfile
open -a Xcode Podfile

Default Podfile should look like this



command for add dependencies:
add 'LibraryName', 'Version'

For ex. going to download AFNetworking
pod 'AFNetworking', '2.2.1'(add just below target 'ProjectNmae' do line)
This tell CocoaPods that you want to install AFNetworking version 2.2.1.

Save and close Podfile.

Now, go to Terminal and type following command for download dependency.
pod install                                                                                         

After completion of download you can see a message

From now on use 'ProjectName.xcworkspace'. 

Go to Project directory and open "ProjectName.xcworkspace".



For more  information Click here

Friday, 30 October 2015

Circular Progress View

iOS framework don't provide pre-build 'Circular Progress View/Bar' like UIProgressBar.
Implementing a 'Circular Progress View' is simple in iOS. Here piece of code for implement 'Circular Progress View'.

1) Create a Sub-Class of UIView Class

@interface CircularProgressView : UIView
{
    CGFloat startAngle;
    CGFloat endAngle;
}
@property (nonatomic, assign) CGFloat percentage;
-(id) initWithFrame:(CGRect)frame;
@end

#import "CircularProgressView.h"

@implementation CircularProgressView

-(id) initWithFrame:(CGRect)frame{
 
  self = [super initWithFrame:frame];
    if (self) {
       
        startAngle = M_PI * 1.5;
        endAngle = startAngle + (M_PI*2);
    }
    return self; 
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    [[UIColor colorWithRed:(CGFloat)235/255 green:(CGFloat)237/255 blue:(CGFloat)236/255 alpha:1] setStroke];
    UIBezierPath *benzierPathBack = [UIBezierPath bezierPath];
    [benzierPathBack addArcWithCenter:CGPointMake(rect.size.width / 2, rect.size.height / 2) radius:(rect.size.width / 2 - 5) startAngle:startAngle endAngle:(endAngle - startAngle) * (100 / 100.0) + startAngle clockwise:YES];
   
    benzierPathBack.lineWidth = 10;
    [benzierPathBack stroke];
   
    CGContextSaveGState(context);
   
    UIBezierPath* bezierPath = [UIBezierPath bezierPath];
   
    // Create our arc, with the correct angles
    [bezierPath addArcWithCenter:CGPointMake(rect.size.width / 2, rect.size.height / 2) radius:(rect.size.width / 2-5) startAngle:startAngle endAngle:(endAngle - startAngle) * (_percentage / 100.0) + startAngle clockwise:YES];
   
    // Set the display for the path, and stroke it
    bezierPath.lineWidth = 10;
    [[UIColor colorWithRed:(CGFloat)1/255 green:(CGFloat)111/255 blue:(CGFloat)37/255 alpha:1] setStroke];
    [bezierPath stroke];  
}


Import CircularProgressView Class, create an object and change percentage value, you can see a 'Circular Progress View'.

Friday, 23 October 2015

Multiform request in Objective c

MultiForm request with NSUrlConnection.  
 
     //Url
    NSString *urlString = @"";

 //Create Url request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
   
    NSString *boundary = @"0xLhTaLbOkNdArZ";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
   
    //Reading the file
    NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.zip"];
    NSData *myData = [NSData dataWithContentsOfFile:filePath];
   
    NSMutableData *body = [NSMutableData data];
   
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%filePath.zip\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:myData];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
   
    [request setHTTPBody:body];
   
    NSError *returnError = nil;
    NSHTTPURLResponse *returnResponse = nil;
   
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&returnResponse error:&returnError];
    if (returnError) {
        NSLog(@"return Error = %@",returnError);
    }
    NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"str = %@",str);
   
    if (returnResponse.statusCode == 200) {
        NSLog(@"Success");
        }
    }

//==========================================
 MultiForm request with AFHTTPNetwork 
//Url
    NSString *urlString = @"";

//Create Operation Manager instance
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

//Prepare Parameter for request
    NSDictionary *postData = @{};

    [manager POST:urlString parameters:dictPostData constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
       //Add file to request
 [formData appendPartWithFileData:imageData name:@"file" fileName:@"filename.jpeg"] mimeType:@"image/jpeg"];

 }success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Response: %@", responseObject);
        if(operation.response.statusCode == 200){
            NSLog(@"Success");
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

Friday, 16 October 2015

Random number in Objective C

Random int between 1 and N
NSUInteger r = arc4random_uniform(N); 


Random int between 1 and N
NSUInteger r = arc4random_uniform(N) + 1; 

Random double between 0 and 1
srand48(time(0)); double r = drand48(); 

Pick a random element from an array
if ([array count] > 0) {  
    id obj = array[arc4random_uniform([array count])]; } 

Generate a Random Lowercase NSString
NSString *letter = [NSString stringWithFormat:@"%c", arc4random_uniform(26) + 'a']; 
Generate a Random Uppercase NSString
NSString *letter = [NSString stringWithFormat:@"%c", arc4random_uniform(26) + 'A'];
Pick a Random character from string
NSString *vowels = @"aeiouy"; 
NSString *letter = [vowels substringWithRange:NSMakeRange(arc4random_uniform([vowels length]), 1)];

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