Translate

Friday 28 March 2014

Geocoding find coordinate from address


Method one instance method

- (void)geocodeFromAddress:(NSString *)address {
    //6
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
        if([placemarks count]) {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            CLLocation *location = placemark.location;
            CLLocationCoordinate2D coordinate = location.coordinate;
            NSLog(@"coordinate = (%f, %f)", coordinate.latitude, coordinate.longitude);
        } else {
            NSLog(@"error");
        }
    }];
}

 Method  two class method this is google api


+(CLLocationCoordinate2D) getLocationFromAddressString:(NSString*) addressStr {

    double latitude = 0, longitude = 0;
    NSString *esc_addr =  [addressStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
    NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
    if (result) {
        NSScanner *scanner = [NSScanner scannerWithString:result];
        if ([scanner scanUpToString:@"\"lat\" :" intoString:nil] && [scanner scanString:@"\"lat\" :" intoString:nil]) {
            [scanner scanDouble:&latitude];
            if ([scanner scanUpToString:@"\"lng\" :" intoString:nil] && [scanner scanString:@"\"lng\" :" intoString:nil]) {
                [scanner scanDouble:&longitude];
            }
        }
    }
    CLLocationCoordinate2D center;
    center.latitude = latitude;
    center.longitude = longitude;
    return center;

}

Wednesday 5 March 2014

Swipe to pop view controller for both IOS 6 and IOS 7

//

//
//
//  Created by Arun Thiru on 25/02/14.
//

#import <UIKit/UIKit.h>

@interface NewNavigationController : UINavigationController

@end

@interface BEWLoginNavigationController ()<UIGestureRecognizerDelegate, UINavigationControllerDelegate>

@property (nonatomic, retain) UISwipeGestureRecognizer *swipeGesture;

@end

@implementation NewNavigationController

#pragma mark - View cycles

- (void)viewDidLoad
{
    [super viewDidLoad];
   
    __weak NewNavigationController *weakSelf = self;
    self.delegate = weakSelf;
   
    self.swipeGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(gestureFired:)];
    [self.view addGestureRecognizer:self.swipeGesture];
}

#pragma mark - gesture method

-(void)gestureFired:(UISwipeGestureRecognizer *)gesture
{
    if (gesture.direction == UISwipeGestureRecognizerDirectionRight)
    {
        [self popViewControllerAnimated:YES];
    }
}

#pragma mark - UINavigation Controller delegate

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    self.swipeGesture.enabled = NO;
    [super pushViewController:viewController animated:animated];
}

#pragma mark UINavigationControllerDelegate

- (void)navigationController:(UINavigationController *)navigationController
       didShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animate
{
    if(![viewController isKindOfClass:[YourViewController class]])
    {
        self.swipeGesture.enabled = YES;
    }
}

@end

Monday 27 January 2014

Find the distance between two geograhical locaions


We need to pass to coordinate to the input to the system and the distance calculated and produced as as output NSNumber
- (NSNumber*)calculateDistanceInMetersBetweenCoord:(CLLocationCoordinate2D)coord1 coord:(CLLocationCoordinate2D)coord2 {
    NSInteger nRadius = 6371; // Earth's radius in Kilometers
    double latDiff = (coord2.latitude - coord1.latitude) * (M_PI/180);
    double lonDiff = (coord2.longitude - coord1.longitude) * (M_PI/180);
    double lat1InRadians = coord1.latitude * (M_PI/180);
    double lat2InRadians = coord2.latitude * (M_PI/180);
    double nA = pow ( sin(latDiff/2), 2 ) + cos(lat1InRadians) * cos(lat2InRadians) * pow ( sin(lonDiff/2), 2 );
    double nC = 2 * atan2( sqrt(nA), sqrt( 1 - nA ));
    double nD = nRadius * nC;
    // convert to meters
    return @(nD*1000);
}


for further reference refer apple guide and here

Sunday 15 December 2013

POST request json

Try the below code

    +(NSData *)postDataToUrl:(NSString*)urlString:(NSString*)jsonString
    {
        NSData* responseData = nil;
        NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        responseData = [NSMutableData data] ;
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
        NSString *bodydata=[NSString stringWithFormat:@"data=%@",jsonString];

        [request setHTTPMethod:@"POST"];
        NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
        [request setHTTPBody:req];
        NSURLResponse* response;
        NSError* error = nil;
        responseData = [NSURLConnection sendSynchronousRequest:request     returningResponse:&response error:&error];
        NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

        NSLog(@"the final output is:%@",responseString);

        return responseData;
    }

Ref: http://stackoverflow.com/questions/5537297/ios-how-to-perform-an-http-post-request

Tuesday 26 November 2013

Fetch record

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntityName"
      inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [self.managedObjectContext
      executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];

Wednesday 13 November 2013

Task Manager

//Header File

typedef void (^TaskBlock)(void);
typedef void (^TaskCompletedBlock)(void);

@interface FCTaskManager : NSObject

-(void)performUITask:(TaskBlock)taskBlock completionBlock:(TaskCompletedBlock)taskCompletedBlock;
-(void)performBackgroundTask:(TaskBlock)taskBlock completionBlock:(TaskCompletedBlock)taskCompletedBlock;

@end



//Implementation

#import "FCTaskManager.h"

@implementation FCTaskManager

-(void)performUITask:(TaskBlock)taskBlock completionBlock:(TaskCompletedBlock)taskCompletedBlock {

    dispatch_async( dispatch_get_main_queue(), ^{

        @autoreleasepool {

            taskBlock();

            dispatch_async( dispatch_get_main_queue(), ^{

                taskCompletedBlock();
            });
        }
    });
}

-(void)performBackgroundTask:(TaskBlock)taskBlock completionBlock:(TaskCompletedBlock)taskCompletedBlock {

    dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        @autoreleasepool {

            taskBlock();

            dispatch_async( dispatch_get_main_queue(), ^{

                taskCompletedBlock();
            });
        }
    });
}

@end
Then I can use the task manager like so:
-(void)viewDidLoad {

    [super viewDidLoad];

    //Create taskManager
    taskManager = [[FCTaskManager alloc] init];

    //Create UIViews, etc WITHOUT blocking main queue
    [taskManager performUITask:^{

        button = [[UIButton alloc] initWithFrame:CGRectMake(30, 30, 300, 300)];
        [button setBackgroundColor:[UIColor redColor]];
        [button setTitle:@"Working" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];

    } completionBlock:^{

        NSLog(@"CREATED BUTTON");

        [self.view addSubview:button];
    }];
}




Dispatch Queue

dispatch_queue_t jsonParsingQueue = dispatch_queue_create("jsonParsingQueue", NULL);
//the name can be anything background 


// execute a task on that queue asynchronously on background 
dispatch_async(jsonParsingQueue, ^{

      [self citySearchArrayMethod]; // populates the city table with city list

    // some code on a main thread (delegates, notifications, UI updates...) 

    dispatch_async(dispatch_get_main_queue(), ^{

      [self.tableView reloadData]; // load the table with data

    });
});