Friday, 12 February 2016

Add PCH file in Xcode6


In the C and C++ programming languages, a header file is a file whose text may be automatically included in another source file by the C preprocessor, usually specified by the use of compiler directives in the source file.

Prefix.pch is a precompiled header file. Precompiled headers were invented to make compiling faster. Rather than parsing the same header files over and over, these files get parsed once, ahead of time.
Xcode 5 and older version of Xcode by default add PCH file with project, but Xcode 6 doesn't include PCH file automatocally.
We can add PCH file in Project.
Here steps to add PCH file in Project:

1) Create new file by selecting File > New File > iOS > Other > PCH File > Next.
2) Give name to newly created file.(Ex- PrefixHeader)
3) Select Project > Targets > Build Setting.
4) Search for 'Prefix header'.
5) Under "Apple LLVM 7.0" you will get the Prefix Header Key.

 6) Type file directory. (Ex- ProjectFolder/ProjeectName-Prefix.pch).
7) Clean project.
8) Build project.

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)];