Wednesday, 7 August 2013

How to get user's current location in your app (iOS programming)

To get current location in iOS:

---> #import <coreLocation/coreLocation.h>
1- Create an instance of CLLocationManager
2- Assign a delegate to the CLLocationManager object
3- Set desiredAccuracy & distanceFilter
4- Call startUpdatingLocation
5- locationManager reports the event to this method ---> locationManager:didUpdateLocations (iOS 6 & Later)


Sample Code:


-----> .h File
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface infinityViewController : UIViewController <CLLocationManagerDelegate>{

    CLLocationManager *locationManager;
}
@end

----> .m File

#import "infinityViewController.h"


@interface infinityViewController ()


@end



@implementation infinityViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
   
    [self getCurrentLocation];
   
   
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getCurrentLocation

{
   
    if (locationManager == nil  )
       
        locationManager = [[CLLocationManager alloc] init];
   
   
   
    locationManager.delegate = self;
   
    locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;

   
    locationManager.distanceFilter = 400;
   
   
   
    [locationManager startUpdatingLocation];
   
}


- (void)locationManager:(CLLocationManager *)manager

     didUpdateLocations:(NSArray *)locations {
       
    CLLocation* currentLocation = [locations lastObject];
   
    NSDate* eventDate = currentLocation.timestamp;
   
    NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
   
    if (abs(howRecent) < 20.0) {
       
       
        NSLog(@"Latitude Value: %+.6f\n",currentLocation.coordinate.latitude);
                   
        NSLog(@"Longitude Value %+.6f\n",currentLocation.coordinate.longitude);
       
    }
   
}

@end

written by: infinitywebseo 

No comments:

Post a Comment