Friday, 1 April 2016

Singleton Class


One of the most used design patterns for developing  iOS application. It's a way to share data between different part of code without having to pass the data around manually.

Singleton is a design pattern that restricts the instantiate of a class to one object. A singleton class returns the same instance no matter how many times an application requests.

Implementation
Create a sub class of NSObject(named: DatabaseHandler)

#import <Foundation/Foundation.h>

@interface DatabaseHandler : NSObject 
     
     +(DatabaseHandler *) sharedInstance
@end


#import "DatabaseHandler.h"

static DatabaseHandler *sharedInstance;
@implementation DatabaseHandler

#pragma mark -
+(DatabaseHandler *) sharedInstance{
   
    @synchronized(self){
       
        if (!sharedInstance) {
            sharedInstance = [[DatabaseHandler alloc] init];
        }
    }
    return sharedInstance;
}

@end

We can declare properties and methods in Singleton class as same like other classes.

 code:

#import <Foundation/Foundation.h>

@interface DatabaseHandler : NSObject 
        @property (nonatomic, strong) NSString *stringValue;
        @property (nonatomic, assign) BOOL check;

       
        +(DatabaseHandler *) sharedInstance
        -(void) initialization;
        -(void) fetchResult;
@end

 goto DatabaseHandler.m

#import "DatabaseHandler.h"

static DatabaseHandler *sharedInstance;
@implementation DatabaseHandler

#pragma mark -
+(DatabaseHandler *) sharedInstance{
   
    @synchronized(self){
       
        if (!sharedInstance) {
            sharedInstance = [[DatabaseHandler alloc] init];
        }
    }
    return sharedInstance;
}


//Initialization at time of creation object(if want to do any operation or set default value, its totally optional)
-(id) init{
    [self initialization];
}
 -(void) initialization{
     check = NO;
     stringValue = @"defaultValue";
}

-(void) fetchResult{
      NSLog(@"Fetch Call");
}
@end


Access to Singleton class methods and properties from outside(another classes)

1)import singleton class.

2) create object for singleton class
DatabaseHandler *databaseHandler = [DatabaseHandler sharedInstance];

3) Set value to property declared in Singleton class
databaseHandler.stringValue = @"New Value";
in the same way
databaseHandler.check = YES;

4) Get value from property declared in Singleton class
NSString *value = databaseHandler.stringValue;
BOOL check = databaseHandler.check;

5)Call methods declared in Singleton class
[databaseHandler fetchResult];

Friday, 18 March 2016

View Animation

A constraint defines a relationship between two user interface objects that must be satisfied by the constraint-based layout system.

For presenting a view with constraint if little bit different.
We can use frame property for animating a view object.
We can change size and origin by setting new value inside animation block.

Here an example for animating 2 UIView object with constraint.

1) Add one UIView object on XIB file.
set following constraint
  a) Leading constraint(Margin from left)  = 0
  b)Tailing constraint(margin from right) = 0
  c) Top constraint(from super view) = 0
  d) Height constraint = 0

2) Add one more UIView object.(for differentiate set different-2 background color)
 set following constraint on newly added UIView object
  a) Leading constraint(Margin from left)  = 0
  b)Tailing constraint(margin from right) = 0
  c) Top constraint (From first UIView object not from super view)= 0
  d)Bottom constraint = 0

Now, define a IBOutlet property for NSLayoutConstraint
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *topHeightConstraint;

On XIB connect topHeightConstraint with Height Constraint of Top or first UIView object.






Add a button for animating both view.
Here action of button

-(void) animationButtonAction:(UIBarButtonItem *)barButton{
    if (self.topHeightConstraint.constant == 0) {
        NSLog(@"Increase height");
        self.topHeightConstraint.constant = 300;
    }
    else{
        NSLog(@"Decrease height");
        self.topHeightConstraint.constant = 0;
    }
    [UIView animateWithDuration:1 animations:^{
        [self.view layoutIfNeeded];
    }];
}


Now, Its all set for animating UIView objects with NSLayoutConstraint.=

Friday, 11 March 2016

CAShapeLayer

CAShapeLayer is a specialized subclass of CALayer that draws itself using the shape you define via the path property. path is an instance of CGPath. We could leverage the convenient UIBezierPath APIs to create a path, and then retrieve the CGPath from it. Besides all the animatable properties inherited from CALayer, there are other animatable properties that let you control attributes such as fill color, stroke color, line thickness, etc.


Set rounded corner of a 'UIView' using "CAShapeLayer" 

//First create a instance of UIView
UIView *rectangleView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 300, 300)];

//set background color of UIView
rectangleView.backgroundColor = [UIColor redColor];

//Add subview to main view
[self.view addSubview:rectangleView];

//Create a instance of CAShapeLayer
CAShapeLayer *shapeLayer = [CAShapeLayer layer];

//set path for CAShapeLayer property's 'path'
UIBezierPath *shapePath =[UIBezierPath bezierPathWithRoundedRect:rectangleView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(10, 10)];

//set CAShapeLayer Path
shapeLayer.path = shapePath.CGPath;

//Add CAShapeLayer to subview
rectangleView.layer.mask = shapeLayer;

By using CAShapelayer we can specify radius for particular corners.

//Set  radius of UIView for Top right and bottom left corners only
UIBezierPath *shapePath =[UIBezierPath bezierPathWithRoundedRect:rectangleView.bounds byRoundingCorners:(UIRectCornerTopRight | UIRectCornerBottomLeft) cornerRadii:CGSizeMake(10, 10)];
    shapeLayer.path = shapePath.CGPath;
    rectangleView.layer.mask = shapeLayer;

Friday, 4 March 2016

UIImagePickerController in Swift

UIImagePickerController  class manages customizable, system-supplied user interface for taking pictures and movies, and for choosing saved images and movies for use in the app. A UIImagePickerController manages user interactions and delivers the results of those interactions to a delegate object.
For more details Click here.

To use an image picker controller with in the app, perform these steps:

1) Verify that the device is capable of picking content from the desired source.
2) Check which media types are available for the source type using.
3) Adjust image picker controller's UI according to media type
4) Present user interface.


Code:

// MARK: - Open Camera
    func openCamera(source:UIImagePickerControllerSourceType){


//Check source type available or not
        if(UIImagePickerController.isSourceTypeAvailable(source) == false){
            return;
        }

//Create new object of UIImagePickerContrller
        let imagepickerController = UIImagePickerController()
       imagepickerController.sourceType = source
        imagepickerController.delegate = self

//Present UIImagePickerContrller user interface
        self.presentViewController(imagepickerController, animated: true, completion: nil)
    }


//MARK: - Image Picker Delegate
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        nameTitlelabel.hidden = false
        //dismiss image picker controller view
        picker.dismissViewControllerAnimated(true, completion: nil)
    }


    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

//Get selected image
        let seletctedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        patientImageView.image = seletctedImage

//dismiss image picker controller view
        picker.dismissViewControllerAnimated(true, completion: nil)
    }

Friday, 26 February 2016

UIAlertController in Swift

A UIAlertController object displays an alert message. This class replaces the UIActionSheet and UIAlertView classes.
In addition to displaying a message, associate actions with alert controller to give a way to respond.
Click Here for more details.

//Display UIAlertView
func displayAlert(){
        let alertController = UIAlertController(title: "Alert Message", message: "Welcome to you", preferredStyle: .Alert)
        alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
        presentViewController(alertController, animated: true, completion: nil)
    }


//Add More action with UIAlertController
func alertOkButtonAction(actionTarget: UIAlertAction){
        print("Ok Action Call")
    }

 //create a action
let OkAction = UIAlertAction(title: "Ok", style: .Default, handler: alertOkButtonAction)
alertController.addAction(OkAction)


//Display alert with  UITextField
alertController.addTextFieldWithConfigurationHandler { (nameTxtFld) -> Void in
           nameTxtFld.textColor = UIColor.blueColor()
        }

//We can also add action on UItextField
 func textChange(txtFld:UITextField){
        let str = txtFld.text! as NSString
        print(str)
       
    }

//Add action on UITextField
alertController.addTextFieldWithConfigurationHandler { (nameTxtFld) -> Void in
           nameTxtFld.textColor = UIColor.blueColor()

           nameTxtFld.addTarget(self, action: "textChange:", forControlEvents: .EditingChanged)
        }

Friday, 19 February 2016

Create a Simple Drawing App

A UIBezierPath object combines the geometry of a path with attributes that describe the path during rendering. We can set the geometry and attributes separately and can change them independent of one another. Once we have the object configured the way you want it, you can tell it to draw itself in the current context. Because the creation, configuration, and rendering process are all distinct steps, Bezier path objects can be reused easily in  code. We can even use the same object to render the same shape multiple times, perhaps changing the rendering options between successive drawing calls. 
For more details about UIBezierPath Click Here.

Now, we are going to create a simple drawing app using UIBezierpath.

First, create a  subclass of UIView Class.
Suppose name is SketchView
 Inside SketchView.h
@interface SketchView : UIView
{
    UIBezierPath *scriblePath;
}


Add following code in SketchView.m

@implementation SketchView

-(instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        scriblePath = [[UIBezierPath alloc] init];
        scriblePath.lineCapStyle=kCGLineCapRound;
        scriblePath.miterLimit=0;
        scriblePath.lineWidth = 2; //Set Stroke with
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    [[UIColor blackColor] setStroke];
    [scriblePath strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}

#pragma mark -
-(void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
     CGPoint touchPoint = [[touches anyObject] locationInView:self.superview];
    [scriblePath moveToPoint:touchPoint];
}
-(void) touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
     CGPoint touchPoint = [[touches anyObject] locationInView:self.superview];
    [scriblePath addLineToPoint:touchPoint];
    [self setNeedsDisplay];
}

@end

 

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.