Thursday, 13 October 2016

Create a bootable USB flash drive in mac

Here i am going to show you, how to create a bootable USB flash drive in mac. In this example i will create a bootable USB flash drive in mac for window installation.

Before begin download ISO image for window. Lots of  online source available for download ISO image for window or you can download from Microsoft software download page.

after completion of download open Terminal.

Type the following command:
$ diskutil list                                                                                                    
above command give the list of all external and internal disk list.
After execution of above above command you can list like below SS






We can see the list of all connected disk. Name is start with disk0, disk1 and so on. Both are internal disk.
Now, connect a USB flash drive to mac. To create a bootable USB drive for a Windows installation, we require a USB drive with the 4 GB of minimum capacity. Larger capacity will be better.
Note: before connect USB drive to mac clear all data from USB drive or format that.
Again  type the previous command and press enter
$ diskutil list                                                                                                          




Now we can see the one more disk(external) in the list. Name of the disk is disk2
Now unmount the external disk.
Unmounting a disk makes it inaccessible by the computer.
Use below command for unmount disk
                                                                                                                          
$ diskutil unmountDisk /dev/disk2                                                                                     
                                                                                                                           
Press enter and we can see the message on terminal
"Unmount of all volumes on disk2 was successful."

Now type the following command

sudo dd if=iso_image_path of=/dev/disk2 bs=1m                                                              

iso_image_path is the location of downloaded window iso image. Get the path of iso image and replace with 'ios_image_path'

Press enter, it will prompt for enter password, enter password and press enter.
It will take some time, may be 30 - 40 mins.

After completion of process it will give message like below image


4145.514462 secs, total time taking for completion of process.

Now eject USB flash disk using following command

$ diskutil eject  /dev/disk2                                                                                                      

Again connect USB disk to mac and can check all files.
Now we have a bootable USB flash drive for window installation.

 

Monday, 10 October 2016

CABasicAnimation

CABasicAnimation provides basic, single-keyframe animation capabilities for a layer property.
CABasicAnimation class animates a layer property between two values, a starting and an ending value. To move a layer from one point to another in its containing window, for example, we can create a basic animation using the keypath position. We give the animation a start value and an ending value and add the animation to the layer.

Here i am going to create a search animation, animation start with a small circle with minimum radius and continue increase the radius and after maximum radius again its start animate the circle from minimum radius.

First create  a Project(SearchActivityIndicatorViewSample)

Now create a new file(SearchActivityIndicatorView) which is subclass of UIView.
We are going to display a animated circle, so for creating a  circle i am going to declare another Class(SearchActivityIndicatorCircleView) inside "SearchActivityIndicatorView".
SearchActivityIndicatorCircleView class also a subclass of UIView.

Ok, Why i am creating a separate class for display a circle?
Answer is, if we want to display more than one circle as a search indicator so we can use multiple instance of that class and we don't need to write code for multiple circle. So by using this approach     we can avoid duplication of code.
 and also declare a property for stroke color inside "SearchActivityIndicatorCircleView Class".

here the code snippet

@interface SearchActivityIndicatorCircleView : UIView
{
   
}
@property (nonatomic, strong) UIColor *strokeColor;
@end


//Implementation 
@implementation SearchActivityIndicatorCircleView

@end


Add the following methods  inside SearchActivityIndicatorCircleView implementation.
-(instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame: frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}


-(void) drawRect:(CGRect)rect{
    //Drawing Code
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextSetStrokeColorWithColor(context, self.strokeColor.CGColor);
    UIBezierPath *circlePath = [UIBezierPath bezierPath];
    [circlePath addArcWithCenter:CGPointMake(self.bounds.size.width/2, self.frame.size.height/2) radius:MIN(self.frame.size.width, self.frame.size.height)/2 - 5  startAngle:DEGREES_TO_RADIANS(0) endAngle:DEGREES_TO_RADIANS(360) clockwise:YES];
    CGPathRef cgPath = CGPathCreateCopy(circlePath.CGPath);
    CGContextAddPath(context, cgPath);
    CGContextSetLineWidth(context, 1);
    CGContextDrawPath(context, kCGPathStroke);
    CGPathRelease(cgPath);
}


In the first method i override initWithFrame: method for creating a new instance for the class.
and in the second method drawRect: i am creating a circle. Radius of circle is not static, its will depend on the frame size of View.
For calculating the radius i used smallest value between width and height and after getting smallest value reduce 5 from the that, and with the resultant value drawing circle.

Now we have enough code for draw a circle, only need to create a instance of a class and as a sub-view.

Now Switch to SearchActivityIndicatorView.h Class and add following codes.
@interface SearchActivityIndicatorView : UIView
{
    CGFloat maxScale, minScale;
}
@property (nonatomic, assign) BOOL isAnimating;
@property (nonatomic, strong) UIColor *strokeColor;
@property (nonatomic, assign) NSTimeInterval animationDuration;

-(void) startSearching;
-(void) stopSearching;


Now switch to SearchActivityIndicatorView.m and add following code
-(instancetype) init{
    self = [super init];
    if (self) {
        [self initializeDefaultValues];
    }
    return self;
}
-(instancetype) initWithFrame:(CGRect)frame{
   
    self = [super initWithFrame:frame];
    if (self) {
        [self initializeDefaultValues];
    }
    return self;
}
-(void) awakeFromNib{
    [super awakeFromNib];
    [self initializeDefaultValues];
}
-(void) initializeDefaultValues{
    //set animation suration
    self.animationDuration = 1.9f;
    //set default stroke color
    self.strokeColor = [UIColor redColor];
    //set minimum scale
    minScale = 0.3f;
    //set maximum scale

    maxScale = 8.0f;
}


First 3 methods are used to creating new instance for the class
and the last method set default value with the time of new instance creation of class.
Inside this method, i am defining default value for animation duration, color of circle' stroke, minimum and maximum scale for circle view.

Now its time to add SearchActivityIndicatorCircleView
-(void) addCircleSearchView{
   //1. get minimum value between width and height
    CGFloat width = MIN(self.frame.size.width, self.frame.size.height)/4;

   //2. Create an instance of SearchActivityIndicatorCircleView
    SearchActivityIndicatorCircleView *circleSearchView = [[SearchActivityIndicatorCircleView alloc] initWithFrame:CGRectMake(0, 0, width, width)];
    [circleSearchView setStrokeColor:self.strokeColor];
    circleSearchView.center = self.center;
    //3.Add CABasicAnimation for scale view
    CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    //4. set animation duration time
    scaleAnimation.duration = self.animationDuration;
    //5. set repeat count to maximum
    scaleAnimation.repeatCount = CGFLOAT_MAX;
    //6. set minimum value for animation
    scaleAnimation.fromValue = @(minScale);
    //7. set maximum value for animation
    scaleAnimation.toValue = @(maxScale);
    //8. set timing function
    scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];

    //9. add animation to Circle layer
    [circleSearchView.layer addAnimation:scaleAnimation forKey:kSearchScaleAnimationKey];
   //10. add SearchActivityIndicatorCircleView as a subview
    [self addSubview:circleSearchView];
}


Above method create an instance for  SearchActivityIndicatorCircleView, add basic animation for animate a circle and add newly created instances as a subview.
Here step by step explanations:
1. Find minimum value between width and height of frame and divide by 4 means the frame of circle view is 4 times less than SearchActivityIndicatorView.
2. Create an instance of  SearchActivityIndicatorCircleView with the minimum frame size.
3. Create an instance of CABasicAnimation with key "transform.scale".
4. set animation duration, the time require for animation of a circle from minimum scale to maximum scale.
5. set repeat count for animation.
6. set minimum scale or starting scale for animation.
7. set maximum scale for animating the circle.
8. timingFunction: A timing function defining the pacing of the animation.
    CAMediaTimingFunction represents one segment of a function describing a timing curve. The
    function maps an input time normalized to the range [0,1] to an
    output time also in the range [0,1]. E.g. these functions are used
    to define the pacing of an animation over its duration (or over the
   duration of one keyframe). Click here for more detail about CAMediaTimingFunction.

9. add animation to circle layer. CABasicAnimation provide capabilities for animate layer property, so we add animation to layer of circle view.
10. Add circle view as a subview.

We have code for draw a circle, add animation to circle.
So,  now its time to display animation, add below code in SearchActivityIndicatorCircleView.m

-(void) startSearching{
   //check if animation is already started
    if (self.isAnimating) {
        return;
    }

   //set flag value true
    self.isAnimating = YES;

  //add circle
    [self addCircleSearchView];
}


 first we are checking, is animation already started if yes than no need to start animation again.
If no than set the flag value true so we can check animation status later.
and last line send a message to  "addCircleSearchView" method for adding a circle view.




Also write a method for stop animation.
-(void) stopSearching{
    if(!self.isAnimating) {
        return;
    }
    for(UIView *searchView in self.subviews) {
        [UIView animateWithDuration:0.9f animations:^{
            searchView.transform = CGAffineTransformMakeScale(7.0f, 7.0f);
            [searchView setAlpha:0.0f];
        } completion:^(BOOL finished) {
            [searchView.layer removeAllAnimations];
            [searchView removeFromSuperview];
        }];
    }
    self.isAnimating = NO;
}


thats enough.
Now Its time for display our effort to end user.
Switch to ViewController.h class, import SearchActivityIndicatorView

add a property IBOutlet  for SearchActivityIndicatorView
@property (nonatomic, weak) IBOutlet SearchActivityIndicatorView *seachActivityIndicatorView;
and add a IBAction for handle user action.
-(IBAction)handleTapGesture:(UITapGestureRecognizer *)sender;

Now switch to  main.storyboard and drag a UIView from Object library.
Select that view and go to identity inspector and change the class from UIView to SearchActivityIndicatorView
 


Connect IBOutlet to SearchActivityIndicatorView.
Add a Tap Gesture Recognizer  to SearchActivityIndicatorView and connect IBAction method.

Now go to ViewController.m class and method for start animation
-(IBAction)handleTapGesture:(UITapGestureRecognizer *)sender{
   
    if (self.seachActivityIndicatorView.isAnimating == YES) {
        [self.seachActivityIndicatorView stopSearching];
    }
    else{
        [self.seachActivityIndicatorView startSearching];
    }
}


Run the app and tap on the screen, we can see a animated circle on screen.
Click here for complete project.

Saturday, 17 September 2016

Blure Effect

Adding blur effect on the view's corner

User interface play an important role in development of a good application. With the useful and important features, it is necessity of a application to make a attractive and good looking user interface. A well design interface force user to play with application and enjoy the application for a time being.

A small small effect can make the interface better like presenting sub-view  with animation or bounce, adding blur effect in the corner of sub-views.
Here i am going to add blur effect in the corner of sub views.
We can achieve blur effect by using gradient. We are having in-build CAGraientLayer in iOS, so its not a tough  to add blur effect in both corner of a view, because of this CAGraientLayer.
Click here for details of CAGraientLayer.

First create a project and add a UIView as a subview of view in the storyboard or xib file.
Than go to .h file and create a outlet for added UIView.

@property (nonatomic, weak) IBOutlet UIView *horizontalLineViewFirst;

again go to storyboard  or xib file and connect the outlet to added UIView.

Now switch to .m file and add a method

#pragma mark - Add Gradient
-(void) addGrandientlayerToView:(UIView *)gradientView{
    //create a gradient layer
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    //set gradient color
    CGColorRef outerColor = [[UIColor colorWithWhite:0.97 alpha:1.0] CGColor];
    CGColorRef innerColor = [[UIColor colorWithWhite:0.72 alpha:0.0] CGColor];

    //set name of the layer
    gradientLayer.name = @"BlurGradientLayer";
    //set color to gradien layer
    gradientLayer.colors = [NSArray arrayWithObjects:(__bridge id)outerColor,(__bridge id)innerColor,(__bridge id)innerColor,(__bridge id)outerColor, nil];
    //set location to each color
    gradientLayer.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0],[NSNumber numberWithFloat:0.200],[NSNumber numberWithFloat:0.710],[NSNumber numberWithFloat:1.0], nil];
    //set start point for draw a gradient layer
    [gradientLayer setStartPoint:CGPointMake(0, 0.6)];
    //set start point for draw a gradient layer
    [gradientLayer setEndPoint:CGPointMake(1, 0.6)];
    //set bound of the layer
    gradientLayer.bounds = gradientView.bounds;
    //set anchor point of layer to {0,0}
    gradientLayer.anchorPoint = CGPointZero;
    [gradientView.layer addSublayer:gradientLayer];

}


pass the message to above method form viewDidLoad method

[self addGrandientlayerToView:self.horizontalLineViewFirst];

Run the  app,  we can see a blur effect on added subview.





 
We can see a effect similar to above image a horizontal line with blur corners.

Now rotate the simulator or device,  one side of blur effect get misplace,its come in the middle not in both corners. Lets fix the issue

add another method to reset gradient location after orientation

#pragma mark -
#pragma mark Handle Orientation

- (void) handleOrientationChange:(NSNotification *)notification{
    [self resetAllGradientLayer];
}
-(void) resetAllGradientLayer{
    [self resetGradientforView:self.horizontalLineViewFirst];
}
-(void) resetGradientforView:(UIView *)gradientView{
    for (CAGradientLayer *layer in gradientView.layer.sublayers){
        if ([layer.name isEqualToString:@"BlurGradientLayer"]) {
            layer.bounds = gradientView.bounds;
        }
    }
}

 
Add orientation change notification to controller

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOrientationChange:) name:UIDeviceOrientationDidChangeNotification object:nil];

 
Now again run the application and check.
Click here for complete project.

Friday, 2 September 2016

Sqlite Database in ios



Sqlite is an in-process library that implement a self-contained,  serverless,  zero-configuration, transactional SQL database engine. Sqlite is very small and light weight, less than 400kiB fully configured or less than 250 KiB with optional features omitted and its not required a separated server process or system to operate.
Click here for more details.

We can use Sqlite for storage data in iOS Application as a database.
This post is related to get data from two different-different database's tables.

First step is to two get both database path.

So create a method which return db path.

-(NSString *) getDbpathWithName:(NSString *)dbName{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
  
    NSString *documentsDir = [paths objectAtIndex:0];
    return [documentsDir stringByAppendingPathComponent:dbName];
}
     

NSString *firstDbPath = [self getDbpathWithName:@"Firstdb.Sqlite"];

NSString *secondDbPath = [self getDbpathWithName:@"Seconddb.Sqlite"];

//declare a Sqlite database instance
sqlite3 *secondDataBase;

//Open second database
if (sqlite3_open([secondDbPath UTF8String], &secondDataBase)!=SQLITE_OK) {
        NSLog(@"Error to open database = %s",sqlite3_errmsg(userDatabase));
        sqlite3_close(userDatabase);
       
secondDataBase = nil;
        return ;
    }
//write a query for attach first database to second database
 NSString *attachQuery = [NSString stringWithFormat:@"ATTACH DATABASE \"%@\" AS aDB",firstDbPath];

//execute query
    sqlite3_exec(
secondDataBase, [attachQuery UTF8String], NULL, NULL, &error);
    if (error) {
        NSLog(@"Error to Attach = %s",error);
        sqlite3_close(userDatabase);
       
secondDataBase = nil;
    }
Now we have attached both database, and can use to get data from both database's tables.

//Write a query to retrieve data
NSString *queryString = @"Select e.id,  e.name,  e.address, ex.car_allowance. ex.medical_allowance, ex.food_allowance from employee e inner join expenses ex on (e.id == ex.empId)".

Here table 'employee' is in first database and table 'expenses' is in second database, because we need to fetch data from two different table so we are using 'join'.

//Now Prepare statement
sqlite3_stmt *selectStmt;
    if (sqlite3_prepare_v2(
secondDataBase, queryString.UTF8String, -1, &selectStmt, NULL) != SQLITE_OK) {
        NSLog(@"Error to prepare annotation select stmt all comment= %s",sqlite3_errmsg(
queryString));
        sqlite3_finalize(selectStmt);
        sqlite3_close(
secondDataBase);
        selectStmt = nil;
       
secondDataBase = nil;
        return;
    }
Its time to fetch all records 
NSMutableArray *empRecordArray = [[NSMutableArray alloc] init];
   
 while (sqlite3_step(selectStmt)==SQLITE_ROW) {
        NSString *empid = [NSString stringWithFormat:@"%s",(const  char*)sqlite3_column_text(selectStmt, 0)];
        NSString *name = [NSString stringWithFormat:@"%s",(const char*)sqlite3_column_text(selectStmt, 1)];
       NSString *address = [NSString stringWithFormat:@"%s",(const char*)sqlite3_column_text(selectStmt,2)]; 
       NSString *car_allowance = [NSString stringWithFormat:@"%s",(const char*)sqlite3_column_text(selectStmt, 3)]; 
       NSString *medical_allowance = [NSString stringWithFormat:@"%s",(const char*)sqlite3_column_text(selectStmt, 4)]; 
       NSString *food_allowance = [NSString stringWithFormat:@"%s",(const char*)sqlite3_column_text(selectStmt, 5)];
      
     NSDictionary *recordDict = @{@"id":empid, @"name":name, @"address":address, @"CarAllowance":car_allowance,@"MedicalAllowance":@"medical_allowance", @"FoodAllowance":food_aalowance};

[empRecordArray addObject:recordDict];
}//end while loop

NSLog(@"All record : %@", empRecordArray);


Check out more post related to




Friday, 26 August 2016

Custom Navigation Transition



One of the cool feature introduce by Apple in iOS7 is custom view controller transitions which make it possible for developer to create own animated transition from one view controller to next view controller.
By default UINavigationController provide right to left animation transition switching one view controller to next view controller and left to right animation transition for back to parent view controller.

But from iOS7, we can add  better interface experience within the app and can give own animation transition for switching one view controller to another view controller.

Here we will create a simple project and  use custom  transition for switching between view controller using UINavigationController Delegate.

Create a new project and embed storyboard in UINavigationController.

Create a new class, subclass of UIVIewController(named ImageCollectionViewController)
ImageCollectionViewController display collection of images in UICollectionView, so switch to ImageCollectionViewController.xib file and add UICollectioView.

Go to main storyboard add a button and set IBAction method
import ImageCollectionViewController to ViewController class and define Button IBAction method.
inside IBAction method  write the code for push to ImageCollectionViewController.

Go to ImageCollectionViewController.h file and add following delegates.
1. UICollectionViewDelegate
2. UICollectionViewDataSource

also add a IBOutlet property for UICollectionView and a property of NSArray for containing all images.



Switch to ImageCollectionViewController.xib file and connect UICollectionView outlet.

Now, go to ImageCollectionViewController.m file

inside viewDidLoad() method set navigationController delegate.
and add images to collectionArrray.

viewDidLoad() will be look like this

Implement UICollectionViewDataSource methods.



Now run the app, we can see the all images.

next step is add another UIViewController subclass(named DetailViewController)
within this class we will display selected image in full screen
Switch to DetailViewController.h file add property for UIImageView and for a UImage.


 go to DetailViewController.xib a add UIImageView and set outlet.

Switch to ImageCollectionViewController.m class, import newly created controller.

Now add UICollectionView Delegate method didSelectItemAtIndexPath:  

Run the app and click on any images we can switch to next view controller(DetailsViewController) with default navigation.

Now go to ImageCollectionViewController.h file and add another delegate UINavigationControllerDelegate 

Add new class , subclass of NSObject(named CustomTransition)
We will add our whole transition code in this class.
UIViewControllerAnimatedTransitioning protocol implement the animations for a custom view controller transition.

Switch to CustomTransition.m file and add delegate methods of UIViewControllerAnimatedTransitioning.

1. set the duration for the transition animation.
-(NSTimeInterval) transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
    return 0.4;
}


 add another another delegate method animateTransition:()
Its perform the transition animations for switching between view controllers.
-(void) animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
   
   
}



Transition context object is created by the system and contain both controller details.

Now its time to add our own code for custom transition
it will be better to write present and dismiss transition inside two different methods.
so add a method for present animation


Above code will perform custom transition for presenting next view controller
Let's go over this step by step
1. get controller to present after transition.
2. get current controller
3. get the view in which the animated transition should take place.
4. Set frame for next controller view
5.add next controller view to animation container view.
6. Scale next controller view to 0.1, so its reduce the size of view 10 times, so it will look too small when transition will start.
7. Animation block for transform next view to original scale.
  after completion the transition remove parent controller view and call method complete transition.

call the presentWithContextTransitioning: from animateTransition:  methos.


Now time to execute our own custom transition, go to ImageCollectionViewController.m file and import our CustomTransition class and add UINavigationControllerDelegate method
-(id<UIViewControllerAnimatedTransitioning>) navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC{
     return [[CustomTransition alloc] init];
}
and in viewDidLoad() set navigation controller delegate
Now run the app and check own cool stuff for switching between two controller.

In the same way we can writer custom transition for dismiss a controller
Here code snap


declare another method in CustomTransition.h and a BOOL variable
@interface CustomTransition : NSObject<UIViewControllerAnimatedTransitioning>
{
    BOOL isReverse;
}
-(instancetype) initWithReverse:(BOOL)value;
@end

define the method inside CustomTransition.m file
-(instancetype) initWithReverse:(BOOL)value;{
    self = [super init];
    if (self) {
        isReverse = value;
    }
    return self;
}

Update animateTransition: method with the following code:

-(void) animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
    if (isReverse == YES) {
        [self dismissWithContextTransitioning:transitionContext];
    }
    else{
        [self presentWithContextTransitioning:transitionContext];
    }
}

Now switch to ImageCollectionViewController and update UINavigationController delegate method



Now run the App and check.

Click here for complete project.


Saturday, 20 August 2016

QRCode Scanner

One of the great feature of AVFoundation framework is the ability of discover  and read bar Codes in real time.
Here i am mainly going to interact (discover and read ) with QR code.

QR(Quick Response) code is a type of matrix barcode or two dimensional barcode uses four standardized encoding mode (numeric, alphanumeric, byte/binary and kanji) to store data (like URLs, Text, Numbers). For more details Click here

For more details about AVFoundation Framework Click here.

Create a new Project
import AVFoundation Framework.

Now go to main storyboard and add a view(Subclass of UIView), a label and a button.

A view will be  display what camera is recording in the form of image.
Label is used for display resultant string data after scanning  QRcode (or the data store in QR code).
And button is for start and stop scanning.

 Now go to ViewController.h file and declare properties.

@property (nonatomic, weak) IBOutlet UIView *previewView;
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UIButton *scanButton;


also declare two more properties
@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;


Back to main storyboard and connect outlets.

Switch to ViewController.m file and add following code inside viewDidLoad method

   //set button corner radious and border color
    self.scanButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.scanButton.layer.borderWidth = 0.7;
    self.scanButton.layer.cornerRadius = 3;
    self.scanButton.clipsToBounds = YES;


    //setting lable color and border
    self.statusLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.statusLabel.layer.borderWidth = 0.7;
    self.statusLabel.layer.cornerRadius = 2;
    self.statusLabel.clipsToBounds = YES;


In the above code we are just adding border color and corner radius on label and button.

Add new method with the name startReading()

-(Void) startReading{
   
    NSError *error;
    

//1. Define capture device
    //For Front Camera
//    AVCaptureDevice *captureDevice = [AVCaptureDevice deviceWithUniqueID:@"com.apple.avfoundation.avcapturedevice.built-in_video:1"];
   
    //For Default Camera
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    

//2.Define Capture Device
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"Error = %@", error.localizedDescription);
        NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey];
        [[[UIAlertView alloc] initWithTitle:@"Camera Unavailable" message:[NSString stringWithFormat:@"The %@ has not been given a permission to your camera. Please check the Privacy Settings: Settings -> %@ -> Privacy -> Camera", appName, appName] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil] show];
        return NO;
    }
    //3.Initialize session
    self.captureSession = [[AVCaptureSession alloc] init];
    [self.captureSession addInput:input]; //add input device to session   
 

 //4.Set metadata output
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    [self.captureSession addOutput:captureMetadataOutput];// Add output data to session
   
    //5. set delegate
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue]; //set delegate 
 

 //6.set the type of metadata objects to process
     [captureMetadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    

//7.Add video preview layer
    self.videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
    [self.videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    self.videoPreviewLayer.frame = self.previewView.bounds;
    [self.previewView.layer addSublayer:self.videoPreviewLayer];
 

//8.Start session  
 [self.captureSession startRunning];
}


1.Capture Device: 

An AVCaptureDevice represents a physical device that provides realtime input media data, such as video and audio. A input device can be the camera or microphone.

2.Capture Device Input:

AVCaptureDeviceInput is a concrete subclass of AVCaptureInput that provides an interface for capturing media from an AVCaptureDevice.

3. Capture Session:
AVCaptureSession is the central hub of the AVFoundation capture classes.To perform a real-time capture, a client may instantiate AVCaptureSession and add appropriate.

4. Capture Metadata Output
AVCaptureMetadataOutput is a concrete subclass of AVCaptureOutput that can be used to process metadata objects from an attached connection. Instances of AVCaptureMetadataOutput emit arrays of AVMetadataObject instances such as detected faces, barcodes.

5.SetDelegate
Sets the receiver's delegate that will accept metadata objects and dispatch queue on which the delegate will be called. A serial dispatch queue must be used to guarantee that metadata objects will be delivered in order.

6. Set metadataObjectTypes:
Specifies the types of metadata objects that the receiver.

7.Preview:
AVCaptureVideoPreviewLayer quickly render the raw data collected by the camera on the screen, means we can also say, AVCaptureVideoPreviewLayer  is display a preview of what the camera is capturing.
AVCaptureVideoPreviewLayer is a subclass of CALayer that we add as a sublayer of preview view's layer.

8.Start the session
 startRunning to start the flow of data from inputs device to outputs data.

Now add delegate method for receive output data.
-(void) captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
   
    if (metadataObjects != nil && [metadataObjects count]>0) {
        id metadataObj= [metadataObjects objectAtIndex:0];
        if ([metadataObj isKindOfClass:[AVMetadataMachineReadableCodeObject class]]) {
            

            AVMetadataMachineReadableCodeObject *barCodeObject;
            barCodeObject = (AVMetadataMachineReadableCodeObject *)[self.videoPreviewLayer transformedMetadataObjectForMetadataObject:(AVMetadataMachineReadableCodeObject *)metadataObj];
          
           
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"metadata readable object count = %d   \n Meta Data = %@",(int)metadataObjects.count,metadataObjects);
                self.statusLabel.hidden = NO;
                [self.statusLabel performSelectorOnMainThread:@selector(setText:) withObject:[metadataObj stringValue] waitUntilDone:NO];
                [self stopReading];
                [self.scanButton setTitle:@"Scan" forState:UIControlStateNormal];
                self.scanButton.enabled = YES;
            });
        }
      
    }
}


add another method for stop reading

-(void) stopReading{
    [self.captureSession stopRunning];
    self.captureSession = nil;
}


Now we have enough code for reading a QRcode, we just need to digger our code.

Add one more method for start and stop reading with user interaction.

Declare a  IBAction method in ViewController.h file
-(IBAction)buttonAction:(id)sender
Go to ViewController.h file and define IBAction method

-(IBAction)buttonAction:(id)sender{
   
    if ([self.captureSession isRunning] == YES) {
        self.statusLabel.hidden = YES;
        self.statusLabel.text = @"";
        [self stopReading];
        [self.scanButton setTitle:@"Scan" forState:UIControlStateNormal];
    }
    else{
        if ([self startReading]) {
            self.statusLabel.hidden = NO;
            self.statusLabel.text = @"Scanning...";
            [self startReading];
            [self.scanButton setTitle:@"Stop" forState:UIControlStateNormal];
        }
       
    }
} 


Now go to main storyboard file and connect IBAction method to button click  event.

Now run the App and scan a QR code, you can see the encoded data in QR code on label.

Click here for complete project.

Saturday, 6 August 2016

Create Custom Camera



iOS provide UIIMagePickerController for getting an image from photo library and for capturing a new image. But iOS also provide a cool feature for creating custom camera. We can create custom camera using AVFoundation framework, which give direct access to the camera and microphone.
This process is managed through AVCaptureSession which coordinate the flow of data from input devices (such as camera, microphone) to outputs (Such as image and movie file).

Minimally we need:

1) An instance of AVCaptureDevice to present the input device, such as a camera and microphone.
2) An instance of a concrete subclass of AVCaptureInput to configure the ports from the input device.
3) An instance of a concrete subclass of AVCaptureOutput to manage the output to a movie file or  still image.
4) An instance of AVCaptureSession to coordinate the data flow from input to output.
5) An instance of AVCaptureVideoPreviewLayer to display a preview of what the camera is recording.



Start session:

    self.session = [[AVCaptureSession alloc] init]; //initialize an instance of AVCaptureSession
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
//Indicates the session preset currently in use by the receiver.

Capture Device: 

An AVCaptureDevice represents a physical device that provides realtime input media data, such as video and audio. A input device can be the camera or microphone.
       
AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

 Capture Device Input:

AVCaptureDeviceInput is a concrete subclass of AVCaptureInput that provides an interface for capturing media from an AVCaptureDevice.

       self.captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error];

Now add capture device input to session
      if ( [self.session canAddInput:self.captureDeviceInput] )
            [self.session addInput:self.captureDeviceInput];


Preview:

AVCaptureVideoPreviewLayer quickly render the raw data collected by the camera on the screen, means we can also say, AVCaptureVideoPreviewLayer  is display a preview of what the camera is capturing.
AVCaptureVideoPreviewLayer is a subclass of CALayer that we add as a sublayer of preview view's layer.

AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
   
    CALayer *rootLayer = [[self view] layer];
    [rootLayer setMasksToBounds:YES];
    [previewLayer setFrame:CGRectMake(0, 0, rootLayer.bounds.size.height, rootLayer.bounds.size.height)];
    [self.PreviewView.layer insertSublayer:previewLayer atIndex:0];


Now, Its enough for display camera recording on screen.

Start the session

[self.session startRunning];

Run the app and check.


Now add a UIButton to the view for capture rendered raw data as a image.

and, for manage the output to a still image create an instance of AVCaptureStillImageOutput and add to session.
AVCaptureStillImageOutput is a concrete subclass of AVCaptureOutput that can be used to capture high-quality still images with accompanying metadata.

AVCaptureStillImageOutput *stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    if ([self.session canAddOutput:stillImageOutput])
    {
        [stillImageOutput setOutputSettings:@{AVVideoCodecKey : AVVideoCodecJPEG}];
        [self.session addOutput:stillImageOutput];
        [self setStillImageOutput:stillImageOutput];
    }


(Add above code before start the session)

Now add button method for capture image,

-(IBAction)captureButtonAction:(id)sender{
    //capture preview image
    [[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:[[self stillImageOutput] connectionWithMediaType:AVMediaTypeVideo] completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
       
        if (imageDataSampleBuffer)
        {
            //get image data from buffer
            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *image = [[UIImage alloc] initWithData:imageData];
        

//save image to photo library (if you want to save captured image)
            [[[ALAssetsLibrary alloc] init] writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:nil];
        }
    }];
}


Now its time to capture fresh image.
Run the app and capture image.


Now Add another method for swap camera(front to back and back to front)
#pragma mark -
-(IBAction) changeCameraAction:(id)sender{
    //disable button
    self.captureButton.enabled = NO;
    self.swapButton.enabled = NO;
    //get current input device
    AVCaptureDevice *currentDevice = self.captureDeviceInput.device;
    AVCaptureDevicePosition preferredPosion = AVCaptureDevicePositionUnspecified;
    AVCaptureDevicePosition currentPosition = currentDevice.position
    ;
    //get new preferred position
    switch (currentPosition) {
        case AVCaptureDevicePositionUnspecified:
            break;
        case AVCaptureDevicePositionBack:
            preferredPosion = AVCaptureDevicePositionFront;
            break;
        case AVCaptureDevicePositionFront:
            preferredPosion = AVCaptureDevicePositionBack;
            break;
    }//end switch case
   
//configure new input device
    AVCaptureDevice *captureDevice = [self deviceWithMediaType:AVMediaTypeVideo withPreferredPosition:preferredPosion];
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:nil];
    //update session
    [self.session beginConfiguration];
    // Remove the existing device input first, since using the front and back camera simultaneously is not supported.
    [self.session removeInput:self.captureDeviceInput];
   
    if ( [self.session canAddInput:deviceInput] ) {
       
        [self.session addInput:deviceInput];
        self.captureDeviceInput = deviceInput;
    }
    else {
        [self.session addInput:self.captureDeviceInput];
    }
    [self.session commitConfiguration];
    //enable button
    self.captureButton.enabled = YES;
    self.swapButton.enabled = YES;
}
-(AVCaptureDevice *) deviceWithMediaType:(NSString *)mediaType withPreferredPosition:(AVCaptureDevicePosition) position{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:mediaType];
    AVCaptureDevice *captureDevice = devices.firstObject;
   
    for ( AVCaptureDevice *device in devices ) {
        if ( device.position == position ) {
            captureDevice = device;
            break;
        }
    }
    return captureDevice;
}


Click here for complete project.