Sunday, 30 April 2017

Display Scrollable Image

In some cases image is bigger than screen size.
For display full image within the screen need to bind that image within the UIScrollView.
Process of binding a image with UIScrollview is easy and can achieve in 5 steps.

Here the step by step process to bind a image with UIScrollView.
1)  Create an instant of UIScrollView.
2)  Get image instant to display
3)  Retrieve width and height of image.
4)  Add UIImageView above to UIScrollView.
5)  Set UIScrollview content size equals to image size.

//Add a UIScrollView
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
scrollView.backgroundColor = [UIColor whiteColor];
[self.view addSubView:scrollView];

//Get Image
UIImage *displayImage = [UIImage imageNamed:@""];

//Get Image Size
CGSize imageSize = displayImage.size;

//Add Image View
UIImageView *displayImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imageSize.width, imageSize.height)];
displayImageView.backgroundColor = [UIColor clearColor];
displayImageView.image = displayImage;
[scrollView addSubView: displayImageView];
[scrollView setContentSize: imageSize];

Sunday, 9 April 2017

Draw a Dashed Pattern Stroke

A small small changes left better impact on UI. In this post we will work on to enhance UI implementation with dashed pattern border on UIView.

Draw dashed pattern border on UIView is very simple and we can use UIBezierPath for draw dashed pattern border.
Lets start, first create subclass of UIView(named DashedBorderView).

#import <UIKit/UIKit.h>

@interface DashedPatternView : UIView

@end


#import "DashedPatternView.h"

@implementation DashedPatternView


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/


@end

Go to DashedPatternView.m and uncomment drawRect: method
Now add following code for draw  a rectangle

- (void)drawRect:(CGRect)rect {
    // Drawing code
    [[UIColor blackColor] setStroke];
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(10, 10)];
    [path addLineToPoint:CGPointMake(rect.size.width, 10)];
    [path addLineToPoint:CGPointMake(rect.size.width, rect.size.height - 10)];
    [path addLineToPoint:CGPointMake(10, rect.size.height - 10)];
    [path closePath];
    path.lineWidth = 2.0;
    [path stroke];
}

 
Go to your controller class and add DashedPatternView as a subview on main view.
Here code

-(void) addBorderView{
DashedPatternView *dashedView = [[DashedPatternView alloc] init];
    dashedView.frame = CGRectMake(100, 300, self.view.frame.size.width-200, 60);
    dashedView.backgroundColor = [UIColor clearColor];
[self.view addSubview:dashedView];

}

Call addBorderView() method from viewDidLoad() method.
Run the app and you can see a rectangle with solid black border
Now we are going to add dashed pattern border instead of solid border
Add following code just before to call stroke method

CGFloat dashes[] = { 6,6,6};
    [path setLineDash:dashes count:3 phase:0];


above two lines of code enough for draw dashed pattern border.
first we have initialize an array for the dashed border style pattern(you can change the pattern and can see result)
second line of code  set pattern for draw with 3 count(Count of pattern array).

Now run the app and you can see a rectangle with dashed pattern border.


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.


Sunday, 5 March 2017

Display a controller on the top of all controller

We have in-build methods to present and navigate a new controller from currently visible controller.
We can use "presentViewController: animated: completion:" method to present a new controller and "pushViewController: animated:" method to push a new controller in navigation controller stack.
But for presenting and navigating a new controller  we must know current visible controller, our presenting and navigation code must be inside the current visible controller file. Suppose our project require to display a controller on notification call, when user receive a notification a controller will present. In this scenario we don't know when the app will receive notification, and at the time of receiving  notification, which controller is on top. So what is the best solution of this problem? first option is write  code inside all classes and call this method on the basis of local notification, when a controller appear its add a observer for present a controller and when its disappear remove that observer. But, is this good option/solution? No, its not a solution of problem. If we accept this approach, than we need to add extra work to controller local notification for present and push controller.  Instead of accepting first approach we will find the current visible controller and present new controller from any where of the application and no need to write same code again and again in side all classes.

In this blog post i am going to find current visible controller and present a new controller.
Lets start,

Go to your project and add new category for UIWindow.
Inside .h file add following methods

- (UIViewController *)visibleViewController;
+ (UIViewController *) getVisibleViewControllerFrom:(UIViewController *) vc;


Now switch to .m file and define methods

- (UIViewController *)visibleViewController {
    UIViewController *rootViewController = self.rootViewController;
    return [UIWindow getVisibleViewControllerFrom:rootViewController];
}

+ (UIViewController *) getVisibleViewControllerFrom:(UIViewController *) vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [UIWindow getVisibleViewControllerFrom:[((UINavigationController *) vc) visibleViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [UIWindow getVisibleViewControllerFrom:[((UITabBarController *) vc) selectedViewController]];
    } else {
        if (vc.presentedViewController) {
            return [UIWindow getVisibleViewControllerFrom:vc.presentedViewController];
        } else {
            return vc;
        }
    }

}
 //--------
In the first method, we are not doing any thing, just we are calling the second method with root controller of window.
In the second method,    we are checking the kind of controller(is a kind of UINavigationController, UITabBarController, presentedViewContrller) and returning top of the controller.

Go to ViewController.m file and import UIWindow category class
 and add below method

-(void) displayFullScreenMessage{
//create a instance of controller
    MessageViewController *controller = [[MessageViewController alloc] initWithNibName:@"MessageViewController" bundle:nil];
    //get main window
    UIWindow *mainWindow =  [[UIApplication sharedApplication] keyWindow];

//get current visible controller
    UIViewController *visiblecontroller = [mainWindow visibleViewController];

//present a controller
    [visiblecontroller presentViewController:controller animated:YES completion:nil];
}


Now we have enough code for display a controller on the top of the controller.
Call the above method and display controller.

Friday, 3 February 2017

Draw a curve on UIView

As we all know, User interface is a key part for all application. User interface of an application is only way to interact with end user. A better user interface provide better experiences to end user.
In this block, we are going to create a curve at the upper part of a view.
Resultant screen will be look line below image


                                                                 


For drawing a curve on the upper part of a view, we need to do some math works for setting the radius and center on view. 
We need 3 things for drawing a curve:
1. Center.
2. Radius
3. Start angle.
4. End angle.
At the initial point we are not having any point and angle.
Suppose, we want to draw a curve on the upper part of view with area w * 100, w is the width of view.
now we have 3 points on the curve
1. view x origin and 100.
2. view center and 0.
3. view width and 100.
so all points are:
initial point - (0, 100)
mid point - (w/2, 0)
end point -  (w, 100).

Now we are having three points, so we can draw a triangle using these points
Lets say our triangle is ∆ABC and ø be the angle opposite to side A.
We can calculate distance between all points of triangle AB, BC and CA

Suppose A is the distance between A and B(AB), similarly B is the distance between BC and C is the distance between CA. 
suppose r be the radius of circle/arc.
then A/sinø = 2r,
This isn't hard (just drop a perpendicular from O to A, and use the definition of sin on the similar triangles).

Area of triangle  ∆ABC
K = (BCsinø)/2
sinø = 2K/BC

Now
2r = A/(2K/BC)
r = ABC/4K

Draw a perpendicular for A to BC, we will get height of triangle which is 100(curve draw area as we defined initially)
so K = (base * height) / 2;
K = B * h / 2;

so radius  r = AC / 2h.
we have calculated radius. lets calculate center
x point of center will be in the mid of the curve area and y point will be radius.
so center c = (w/2, r)

now we are ready for draw a curve on the upper part of a view.

Sub-classing of view is the best option for customization and redrawing.
Create a new class(subclass of UIView) namely CurveView(you can choose any name for a class)

in a CurveView.h file declare the following methods and variables
//----variables
    CGFloat radius;
    CGPoint centerPoint;
    CGFloat curveTopMargin;

//----methods
-(instancetype) initWithFrame:(CGRect)frame withUpperCurveMargin:(CGFloat)topMargin;

also declare a macro for convert angle from degree to radians
#define   DEGREES_TO_RADIANS(degrees)  ((M_PI * degrees)/ 180)

Switch to CurveView.m file and following code
//method for initialize an instance of CurveView
-(instancetype) initWithFrame:(CGRect)frame withUpperCurveMargin:(CGFloat)topMargin{
    self = [super initWithFrame: frame];
    if(self){
        curveTopMargin = topMargin;
        [self calculateRadius];
    }
    return self;
}

Now add code for calculate center point and radius
#pragma mark - Calculate radius and center
-(void) calculateRadius{
    CGFloat a = [self calculateDistance:CGPointMake(0, curveTopMargin) andPoint:CGPointMake(self.frame.size.width/2, 0)];
    CGFloat c = [self calculateDistance:CGPointMake(self.frame.size.width, curveTopMargin) andPoint:CGPointMake(self.frame.size.width/2, 0)];
    radius = (a * c)/(2*curveTopMargin);
    centerPoint = CGPointMake(self.frame.size.width/2, radius);
}
-(CGFloat) calculateDistance:(CGPoint)p1 andPoint:(CGPoint)p2{
    CGFloat x =sqrt((pow((p2.x - p1.x), 2)+(pow(p2.y - p1.y, 2))));
    return x;
}


And now add drawRect() method for drawing a view with curve
- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    //-------draw
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextSetFillColorWithColor(context, [UIColor cyanColor].CGColor);
    UIBezierPath *curvePath = [UIBezierPath bezierPath];
    [curvePath addArcWithCenter:centerPoint radius:radius-1  startAngle:DEGREES_TO_RADIANS(0) endAngle:DEGREES_TO_RADIANS(360) clockwise:YES];
    CGPathRef cgPath = CGPathCreateCopy(curvePath.CGPath);
    CGContextAddPath(context, cgPath);
    CGContextSetLineWidth(context, 1);
    CGContextSetShadowWithColor(context, CGSizeMake(0, -1.0), 0.3, [UIColor lightGrayColor].CGColor);
    CGContextDrawPath(context, kCGPathEOFillStroke);
    CGPathRelease(cgPath);
    CGContextRestoreGState(context);
}


Go to controller class and add curve view as a subview
-(void) addCurveView{
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CurveView *topCurveView = [[CurveView alloc] initWithFrame:CGRectMake(0, screenSize.height, screenSize.width, 250) withUpperCurveMargin:60];
    topCurveView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:topCurveView];
    CGRect f = topCurveView.frame;
    f.origin.y = screenSize.height - f.size.height;
    [UIView animateWithDuration:0.3 animations:^{
        topCurveView.frame = f;
    }];
}


Run the app, w can see a curve at the upper part.

Click here for Complete project.

Thursday, 19 January 2017

Getting Current Location

The Core Location Framework provide the Objective-C interface for obtaining information about current location and heading(direction in which device is pointing) of user. By using this framework we can configure and schedule delivery of location and heading event and can define geographic regions.

Get current location:
CLLocationManager class have ability to deliver current location and heading event. We can use this class for start and stop delivery of  location and heading event. Its provide all event information through delegates methods(CLLocationManagerDelegate).

Here code snippet for getting current location

-(void) getCurrentLocation{
    //Create an instance of CLLocationManager
    CLLocationManager * locationManager = [[CLLocationManager alloc] init];

    // Set delegate
    locationManager.delegate = self;

   // set accuracy
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    //request for authorization
    if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [locationManager requestWhenInUseAuthorization];
    }

    //start updating locations
    [locationManager startUpdatingLocation];
}


Now define the delegate method for getting location inforamation

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *currentLocation = [locations lastObject];
    NSLog(@"Location latitude - %f",currentLocation.coordinate.latitude);
    NSLog(@"Location longitude - %f", currentLocation.coordinate.latitude);
}

// get error message to fetch location
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
}

Its enough for getting current location of user.
Run the app.
First its prompt a message for getting accessibility to use current location(This message will appear  first time only). Click on allow button and  we can see location info in console area.

Note: For running the application on simulator, we need to do some extra setting, because by default simulator location is set to 'None' and this is the reason we are getting error message instead of current location information.
Now select 'Location' under Debug menu option of simulator, and choose 'custom location'. We can see some value for latitude and longitude, it is the position of Apple or Apple store,  we can change latitude and longitude value. Now click on 'Ok' and run the app again.
we can see  latitude and longitude value on console area.

Now we are getting current location of user in the form of latitude and longitude, but is it enough to find address/location by a user?  If i provide my latitude and longitude details to some one , is it possible to find my location for that?
We are getting current location information but its not understand for user. So we are going to convert location info in human readable format.

No need to worry about conversion because Core Location framework has ability to perform this task by CLGeocoder.
CLGeocoder:
The CLGeocoder class provides services for converting coordinate(latitude and longitude) to the user-friendly representation. A user-friendly representation of the coordinate typically consists of the street, city, state, and country information corresponding to the given location, but it may also contain a relevant point of interest, landmarks, or other identifying information. 

 Now back to code and update locationManager: didUpdateLocations: method with below code

 -(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    //stop updating locations
    [manager stopUpdatingLocation];
    //get current location
    CLLocation *currentLocation = [locations lastObject];
    NSLog(@"Location latitude - %f",currentLocation.coordinate.latitude);
    NSLog(@"Location longitude - %f", currentLocation.coordinate.latitude);
 
    //convert coodinate to user-friendly representation
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:locations.lastObject completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *placeMark = [placemarks lastObject];
        NSLog(@"name = %@", placeMark.name);
        NSLog(@"address dict = %@",placeMark.addressDictionary);
    }];
}


Run the application again.
Now we can see address details in console area.



Sunday, 15 January 2017

Contact Picker Controller

One of the useful framework provided by Apple is "ContactsUI Framework". ContactUI Framework display user's contact list in a graphical interface.  The ContactUI Framework is useful for display, edit, select and create contact within the app. Before enter in code lets discuss about some important classes of this framework.

CNContactPickerViewController:
CNContactPickerViewController present the entire list of contact to user. This class allows to user to select one or multiple contacts. Its supports both single selection and multi-selection. The app does not need access to the user’s contacts and the user will not be prompted for access. It will only have access to the final selection of the user.

CNContactViewController:
The CNContactViewController is used to display a contact. It can display a new contact, unknown contact, or existing contact.

Now we are ready for display entire list of contacts  within the application.

Here code snippet for  display CNContactPickerViewController
//Create an instance of  CNContactPickerViewController
CNContactPickerViewController *contactController = [[CNContactPickerViewController alloc] init];
//Set the CNContactPickerDelegate
    contactController.delegate = self;
//Present picker controller
    [self presentViewController:contactController animated:YES completion:nil];

Implement the delegate method  for getting details of selected contant.
(In this example we are going to handle onle single selection of contact)

 - (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{
            NSLog(@"Given Name = %@",contact.givenName);
           //Get numbers
           NSArray *phoneNumbers= contact.phoneNumbers;
    for(CNLabeledValue *phoneNumber in phoneNumbers){
        if ([phoneNumber isKindOfClass:[CNLabeledValue class]]) {
            NSLog(@"CNLabeledValue - %@", ((CNLabeledValue *)phoneNumber).value);
            id valueType = ((CNLabeledValue *)phoneNumber).value;
            if ([valueType isKindOfClass:[CNPhoneNumber class]]) {
                    NSLog(@"phone number - %@",[valueType valueForKey:@"digits"]);
                    NSLog(@"Country -> %@", [valueType valueForKey:@"countryCode"]);
            }
         }
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}


// contactPickerDidCancel invoked, when user cancel picker selection
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


For more detail Click here