Showing posts with label tutorials. Show all posts
Showing posts with label tutorials. Show all posts

Sunday, 2 July 2017

Create PCH file in Xcode 6


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.

Monday, 26 June 2017

Circular Progress Bar Indicator

iOS 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'.

Sunday, 18 June 2017

Drawing on View

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

Sunday, 11 June 2017

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


Sunday, 4 June 2017

Core Animation

Core Animation is a graphics rendering and animation infrastructure use to animate the views and other visual elements. Core Animation is not a replacement for app’s views. Instead, it is a technology that integrates with views to provide better performance and support for animating their content. All you have to do is configure a few animation parameters (such as the start and end points) and tell Core Animation to start. Core Animation does the rest, handing most of the actual drawing work off to the onboard graphics hardware to accelerate the rendering. This automatic graphics acceleration results in high frame rates and smooth animations without burdening the CPU and slowing down your app.

Below code add "Pulse Effect" animation.

//Create a CALayer
CALayer *animatelayer = [CALayer layer];
//Setting Frame for CALayer
animatelayer.frame = CGRectMake(0,0, 160, 160);
//Setting Color for CALayer
animatelayer.backgroundColor = [UIColor redColor].CGColor;
//Setting Position for CALayer
animatelayer.position = (CGPoint){CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds)};
//Setting Corner radius for CALayer to look like a Circle
animatelayer.cornerRadius = 80;

//Create a Basic Animation
CABasicAnimation *theAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
theAnimation.duration=2.0;
theAnimation.repeatCount=HUGE_VALF;
theAnimation.autoreverses=YES;theAnimation.fromValue=[NSNumber numberWithFloat:0.7];
theAnimation.toValue=[NSNumber numberWithFloat:0.0];

//Add animation to CALayer
[animatelayer addAnimation:theAnimation forKey:@"animateOpacity"];

//Add CALayer to View
[self.view.layer insertSublayer:animatelayer atIndex:0];

For details Click here

Sunday, 28 May 2017

Frame Animation with CGAffineTransform

One of the most powerful and useful property of UIView is transform, which takes a CGAffineTransform. This is a matrix that express how each pixel of UIView should be modified, applying some mathematical formulas.

CGAffineTransformScale: CGAffineTransformScale use for scale a view up and down. A transform value of 5.0 means make the view 5 times bigger than actual frame.

CGAffineTransformRotate: Use for rotate a view by given angle. It uses radian.


Here a piece of code for render a view  with animation from center.

UIImageView *aniView;

//method for display subview.
-(void) displaySubView{
    //Create object for sub view
    if (!aniView) {
        aniView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.center.x, self.view.center.y, 0, 0)];
        aniView.backgroundColor = [UIColor clearColor];
        aniView.image = [UIImage imageNamed:@"imagename.png"];
        aniView.clipsToBounds = YES;
        aniView.center = self.view.center;

      // Reduce view to 1/10th of its original frame
        aniView.transform = CGAffineTransformScale(aniView.transform, .01, .01);
        [self.view addSubview:aniView];
    }
    [UIView animateWithDuration:1 animations:^{

        // return the view to original frame
        aniView.transform = CGAffineTransformScale(aniView.transform, 100, 100);
      
    }];
}

//Method for hide subview
-(void) hideSubView{
    [UIView animateWithDuration:1 animations:^{
        aniView.transform = CGAffineTransformScale(aniView.transform, .01, .01);
    }];
}

Sunday, 7 May 2017

UITableView in Swift

Adding a Table View in swift is same as Objective-C.
Create a new Single View Application and give any name you want,  make sure you select 'Swift' language.


 Go to  storyboard and add UITableView, make a IBOutlet for Table view
Now, switch to ViewController .swift class and add UITableViewDelegate and UITableDataSource

Class RolePopOverViewController: UIViewController, UITableViewDelegate,UITableViewDataSource{
  
// IBOutel for UITableView
     @IBOutlet weak var roleTableView: UITableView!  

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
  

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


Note: You can see a error "Type ViewController does not conform to Protocol  ''UITableViewDataSource' ". Its just because we didn't add two required Table View Data Source Method yet.

create a NSArray instance  globally
var allRoleDataArray : NSArray!

Now register UITableViewCell class
roleTableView .registerClass(UITableViewCell.self, forCellReuseIdentifier: "CellIdentifier")
//initialize globally declare array
 allRoleDataArray = ["One","Two","Three","Four","Five"]

Add above lines in viewDidLoad()

Now time to add UITableView Data Source method

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allRoleDataArray.cout  
 }


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
       
        let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
        var value : NSString = allRoleDataArray[indexPath.row] as NSString
        cell.textLabel?.text = value
        return cell;
    }


you can't see error any more.
Build and run the app.
Now  open ViewController.swift and add ''didSelectRow'' method

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var value : NSString = allRoleDataArray[indexPath.row] as NSString
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        NSLog("Selected Row = %@", value)
    }


Again run the App and select any row you can see some message on console.
Ex: if you select second row you can see "Selected Row = Two"

Thursday, 30 March 2017

Get User Current Location

Location service improve the app by enhancing user experience. Lots of application's features base on location service like finding near places, restaurant and whatever user want to search. Uber, Ola, Nearby and tons of applications are based on location service and display required content on the basis of that. Suppose we are stand on a place and want to search restaurant near current location, in this case we must know user current location and than can display result according to user search.
Now question is how can we get user current location? It is not a difficult task, every language provide in build framework and library for perform this task.
 Apple provide Core Location Framework for obtaining all necessary information regarding user's current location. Core Location Framework provide geographic location of device. Click here to know about Geographic coordinate system.

Lets start the coding stuff to fetch current location of a user.
Add Core Location Framework in the build phase of target under"Link Binary with Library"  section, switch to controller class and import location framework and implement <CLLocationManagerDelegate> and declare an instance of CLLocationManager.

#import <CoreLocation/CoreLocation.h>
@interface HomeMapViewController : UIViewController<CLLocationManagerDelegate>{
            CLLocationManager *locationManager;
}
@end

Now switch to .m class and add method for fetch current location

@implementation HomeMapViewController
      - (void)viewDidLoad {
              [super viewDidLoad];
              // Do any additional setup after loading the view from its nib.
               [self  getCurrentLocation];
       }
     -(void) getCurrentLocation{
         locationManager = [[CLLocationManager alloc] init];
         locationManager.delegate = self;
         locationManager.desiredAccuracy = kCLLocationAccuracyBest;
         if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
             [locationManager requestWhenInUseAuthorization];
         }
         [locationManager startUpdatingLocation];
     }
// define delegate methods of <CLLocationManagerDelegate>
      - (void)locationManager:(CLLocationManager *)manager
         didFailWithError:(NSError *)error{
          NSLog(@"Error to fetch location = %@", error);
     }
     -(void) locationManager:(CLLocationManager *)manager didUpdateLocations:               (NSArray<CLLocation *> *)locations{
         CLLocation *location = [locations lastObject];
         CLLocationCoordinate2D cord = location.coordinate;
         NSLog(@"Current Location\n Latitude - %f \n Longitude - %f", cord.latitude, cord.longitude);
     }@end

Now run the app and allow the application to fetch your current location.
You can see latitude and longitude value of location on  console area. We are successfully getting  current location of device/user.
We can stop location update service any time by using 'stopUpdatingLocation' method. It will be better to stop location service after getting current location. add following  line of code inside of 'didUpdateLocations' method

[locationManager stopUpdatingLocation];

But the problem is, value of location in form of latitude and longitude and it is not in human readable address. Lets convert the coordinate value in human readable address.

CLGeocoder class provide service for convert coordinate to human readable address. By specify the latitude and longitude of a given location, you can use CLGeocoder to find a user-readable address.

Lets create a new method for getting human readable address of coordinate.

-(void) getReadableAddressFrom:(CLLocation *)location{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
        if (error == nil && [placemarks count] > 0) {
            CLPlacemark *placemark = [placemarks lastObject];
            NSString *address = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",placemark.subThoroughfare, placemark.thoroughfare,placemark.postalCode, placemark.locality,placemark.administrativeArea,placemark.country];
            NSLog(@"Address = %@", address);
        } else {
            NSLog(@"%@", error.debugDescription);
        }
    } ];
}


Inside 'didUpdateLocations' method add line of code to call above method.
[self getReadableAddressFrom:location];

Run the code and check the console, you can see address details.

Note :   For running the application on simulator set the default address of simulator.
In the menu bar, select “Debug” -> “Location” for setting the simulator location.


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.

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.

Saturday, 16 July 2016

Custom Input View For System Keyboard



ios allows apps to display custom input views for the system keyboard. It also enables apps to have an accessory view above the system keyboard or custom input view. Additionally, it enables apps to play key-click sounds when users tap on a controls of an input view or input accessory view.
We can display UIPicker, Color Picker and any other custom view instead of system keyboard. I am going to display a UIPickerView for a keyboard.

Here a sample code for display custom input view for the system keyboard.

First create a sub class of UIView, (named "CustomFontSelectionView").

#import <UIKit/UIKit.h>
@interface CustomFontSelectionView : UIView

#import "CustomFontSelectionView.h"
@implementation CustomFontSelectionView


 Now add a UIPicker of Subview, 
 first declare a instance of UIPicker class in file CustomFontSelectionView.h  file
 and a Array  for containing all objects.

@interface CustomFontSelectionView : UIView<UIPickerViewDelegate, UIPickerViewDataSource>
{
    UIPickerView *pickerView;
    NSArray *fontListArray;
}


add below code in  CustomFontSelectionView.m

-(instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}
-(void) initialize{
    fontListArray = @[[NSNumber numberWithInteger:10],[NSNumber numberWithInteger:11],[NSNumber numberWithInteger:12],[NSNumber numberWithInteger:13],[NSNumber numberWithInteger:14],[NSNumber numberWithInteger:15],[NSNumber numberWithInteger:16],[NSNumber numberWithInteger:17],[NSNumber numberWithInteger:18],[NSNumber numberWithInteger:19],[NSNumber numberWithInteger:20],[NSNumber numberWithInteger:21],[NSNumber numberWithInteger:22],[NSNumber numberWithInteger:23],[NSNumber numberWithInteger:24],[NSNumber numberWithInteger:25]];
    pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    pickerView.delegate = self;
    pickerView.dataSource = self;
    [self addSubview
:pickerView];
}

#pragma mark -
#pragma mark Picker View DataSource
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return fontListArray.count;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
#pragma mark Picker View Delegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [NSString stringWithFormat:@"%@",[fontListArray objectAtIndex:row]];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    //send delegate to update text with selected font size
    if (self.fontDelegate && [self.fontDelegate respondsToSelector:@selector(didSelectFontSize:)]) {
        [self.fontDelegate didSelectFontSize:[fontListArray objectAtIndex:row]];
    }
} 




Now import Newly created Class to ViewController class
#import "CustomFontSelectionView.h"

and declare a instance variable for Class object
CustomFontSelectionView *customFontSelectionView; (a variable or instance always declare inside Interface Section)

Now go to ViewController and add a UITextField(either by code or by Xib, we can use any way).
and declare a instance of UITextField inside ViewController.h class.
In case of adding a UITextField using Xib connect IBoutlet with declared UITextField.


Add UITextField by code 
Declare a UItextField instance in ".h" file (named textField).
  
@property (nonatomic, strong)  UITextField *textField;

In ViewController.h
 Add following  code to ".m" file
Inside viewDidload method add code for display  Custom view.
self.textField = [[UITextFiled alloc]initWithFrame:CGRectMake(0, 0, self.view.bound.size.frame, 150)];
 [self.view addSubView: self.textField];

Now initialize Custom View

#pragma mark -
-(void) displayFontSelectionView{
    [self.textField resignFirstResponder];
    if (!customFontSelectionView) {
        customFontSelectionView = [[CustomFontSelectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, height)];
    }
    customFontSelectionView.fontDelegate = self;
    self.textField.inputView = customFontSelectionView;
    [self.textField becomeFirstResponder];
}


Add following piece of code just below  " [self.view addSubView: self.textField];"

self.textField.inputView = customColorSelectionView;

We can also add a Input Accessory view with a keyboard(Appear just above keyboard) in the same way
Add a UIToolbar either using Xib or code and add as a input accessory view.

self.textField..inputAccessoryView = self.toolBar; 


Click here for complete project.