3

I have to find the current location and i am using this code

 -(CLLocationCoordinate2D) getLocation{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
return coordinate;

}

- (void)getCurrentLocation{
    CLLocationCoordinate2D coordinate = [self getLocation];
    NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude];
    NSLog(@"Latitude  = %@", latitude);
    NSLog(@"Longitude = %@", longitude);
}

but latitude and longitude is coming zero? and i have called these method in viewDidLoad

[self getCurrentLocation];
[self getLocation];

why is it so please help me. thanks

  • why down vote if you know the answer then post here? –  May 31 '16 at 06:20
  • 2
    You are doing it wrong. You need to use `CLLocationManagerDelegate` methods to get the coordinates. You need to read the [Apple Doc](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html) – iphonic May 31 '16 at 06:20
  • which method i have to use ? –  May 31 '16 at 06:21
  • @iphonic i am trying but not working tell me what to do/ –  May 31 '16 at 06:54
  • What to do: Read the documentation. If you need someone to tell you, any Mac can also read the documentation to you. – gnasher729 May 31 '16 at 07:42

6 Answers6

3

I hope , Following info can help you:

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

@interface yourController : UIViewController <CLLocationManagerDelegate> {
    CLLocationManager *locationManager;
}

@end

and add this:

    locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    [self.locationManager requestWhenInUseAuthorization];

[locationManager startUpdatingLocation];

Callback function

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}

You also have to add a string for the

[`NSLocationAlwaysUsageDescription`]
Suraj Sukale
  • 1,778
  • 1
  • 12
  • 19
  • no error is coming bro didupdatelocations is not executing –  May 31 '16 at 07:15
  • thank you @Suraj But it is updating again and again how to stop it or how to set timer so that after some fix time it will update –  May 31 '16 at 07:36
  • 1
    set like this--- locationManager.distanceFilter=20 ( set this value as per your requirement) ; It filters out short moves.and you get location update only when user moves greater than 20 meters. – Suraj Sukale May 31 '16 at 08:32
  • 1
    I think, locationManager.distanceFilter=(any value); this solve your issue....but if you want to know more about timer then use this------- NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timerCalled) userInfo:nil repeats:NO]; -(void)timerCalled { NSLog(@"Timer Called"); // Your Code } – Suraj Sukale May 31 '16 at 08:44
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/113394/discussion-between-aakash-and-suraj-sukale). –  May 31 '16 at 10:06
2

You need to use "CLLocationManagerDelegate".

Just go through this tutorial. How To Get the User Location in iPhone App

Here you will learn about CoreLocation Framework.

This is the delegate method which will return you current lat-long.

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

And also make sure your app authorize to use location services.

And Also run your app on device, or if you want to see the result in simulator, follow the steps mentioned in tutorial.

Step 1 : #import <CoreLocation/CoreLocation.h> import framework. Also add framework in your project.

Step 2 : Make sure your view-controller implement CLLocationManagerDelegate

@interface MyLocationViewController : UIViewController <CLLocationManagerDelegate>

Step 3 : Define class instance of CLLocationManager

@implementation MyLocationViewController {
    CLLocationManager *locationManager;
}

Step 4 :

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    locationManager = [[CLLocationManager alloc] init];

    if([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            //iOS 8.0 onwards
            [locationManager requestAlwaysAuthorization];
        }
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [locationManager startUpdatingLocation];
}

Step 5 : Here is your CLLocationManagerDelegate method implementation

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
    UIAlertView *errorAlert = [[UIAlertView alloc]
                                    initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil) {
       NSLog(@"Longitude %.8f",currentLocation.coordinate.longitude);
       NSLog(@"Latitude %.8f",currentLocation.coordinate.latitude);
    }
}
Wolverine
  • 4,264
  • 1
  • 27
  • 49
1

First go to your info.plist and right click on it and select the source code option. enter image description here

Then add the following lines after the <dict> keyword

    <key>NSLocationAlwaysUsageDescription</key>
    <string>This App wants to Know your location</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>This App wants to Know your location</string>

Without this, you can't get CLLocation working in iOS 9.0.

Now follow the instruction.

Import

#import <CoreLocation/CoreLocation.h>

and list the CoreLocation delegate like

@interface ViewController ()<CLLocationManagerDelegate>

@property (strong, nonatomic) CLLocationManager *locationManager;

@end

Then in the viewDidLoad method add the following lines-

    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate=self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
        [self.locationManager requestWhenInUseAuthorization];
    }
    [self.locationManager startUpdatingLocation];

Now implement the delegate methods

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
    UIAlertView *errorAlert = [[UIAlertView alloc]
                               initWithTitle:@"Sorry" 
                               message:@"Failed to Get Your Location"      
                               delegate:nil 
                               cancelButtonTitle:@"OK"  
                               otherButtonTitles:nil];
    [errorAlert show];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil) {
        NSLog(@"%@", [NSString stringWithFormat:@"%.4f", currentLocation.coordinate.longitude]);
        NSLog(@"%@", [NSString stringWithFormat:@"%.4f", currentLocation.coordinate.latitude]);
    }
}
Natasha
  • 6,651
  • 3
  • 36
  • 58
0

It takes some time for the CLLocationManager to get the coordinates. Therefore, the CLLocationManager uses a delegate to notify when it received the location updates. Therefore, you cannot get the result immediately. Please have a look at this post to see how it's done.

Community
  • 1
  • 1
Ruchira Randana
  • 4,021
  • 1
  • 27
  • 24
0

Well, I wanted you to read the doc, still I am posting the solution.

-(void)viewDidLoad{
     [self initLocationManager];
}


-(void)initLocationManager{

    self.locationManager=[[CLLocationManager alloc] init];
    self.locationManager.delegate=self;
    if (([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) {
        [_locationManager requestWhenInUseAuthorization];
    }
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    [self.locationManager startUpdatingLocation];

}

Then handle the location updates in the CLLocationManager delegate method like below

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    // If it's a relatively recent event, turn off updates to save power.
    CLLocation* location = [locations lastObject];
    NSDate* eventDate = location.timestamp;
    NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
    if (abs(howRecent) < 15.0) {


        NSLog(@"%f,%f",location.coordinate.latitude,location.coordinate.longitude);


    }
}

Update

To make it work, you need to do two things

  1. Enable Background Modes from Capabilities Tab, and choose Location Updates, see image below

    enter image description here

  2. Add NSLocationWhenInUseUsageDescription in Info Tab, into the plist, see image

    enter image description here

It will start working.

Hope it helps. Cheers.

iphonic
  • 12,615
  • 7
  • 60
  • 107
  • it is not working brother not showing anything even method is not executing –  May 31 '16 at 07:08
  • -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ this method is not executing –  May 31 '16 at 07:12
  • @aakash See my Update. – iphonic May 31 '16 at 07:21
  • it is working now thank you very much for you help but how to stop updating latitude and longitude again and again in 0.1millisecond –  May 31 '16 at 07:35
  • Just call [self.locationManager stopUpdatingLocation]; when you want to stop it. – iphonic May 31 '16 at 07:48
0

Use this code it works

firstly add NSLocationAlwaysUsageDescription as string in info.plist

in .h

#import <CoreLocation/CoreLocation.h>

@interface ExamListVC : UIViewController<CLLocationManagerDelegate>
{
    CLLocationManager * locationManager;
}
@end

in .m use this code

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    locationManager . delegate = self;

    [self initLocationManager];
}

    -(void)initLocationManager
    {
        locationManager=[[CLLocationManager alloc] init];
        locationManager.delegate=self;
        if (([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]))
        {
            [locationManager requestWhenInUseAuthorization];
        }
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        locationManager.distanceFilter = kCLDistanceFilterNone;
        [locationManager startUpdatingLocation];

    }


    -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    {
        CLLocation* location = [locations lastObject];
        NSDate* eventDate = location.timestamp;
        NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
        if (abs(howRecent) < 15.0)

        {
            NSLog(@"Current Coordinates are  %f,%f",location.coordinate.latitude,location.coordinate.longitude);
            [locationManager stopUpdatingLocation];
            }
        }

it will give output like

[2390:96060] Current Coordinates are 37.332331,-122.031219