Bobby W
Bobby W

Reputation: 824

iOS 8 CLLocationManager

I am trying to just NSLog co-ordinates in my console, but it is not working.

I have the core location linked in header

@implementation ViewController {
    CLLocationManager *locationManager;
}

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

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

    [locationManager startUpdatingLocation];
}

- (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(@"%f", currentLocation.coordinate.longitude);
        NSLog(@"%f", currentLocation.coordinate.latitude);
    }
}

But I am not getting anything in the console, does anybody know what could be going wrong?

Upvotes: 0

Views: 190

Answers (1)

Sebyddd
Sebyddd

Reputation: 4315

Since iOS 8 you have to ask for user's permission before starting to update the location. Before that you have to add the messages that the user will receive alongside the request for permission. In your .plist file add those 2 keys (if you want to use both types of location fetching) and fill them with your own message: NSLocationWhenInUseUsageDescription ,NSLocationAlwaysUsageDescription

enter image description here

Afterwards ask for permission, right before starting the CLLocationManager:

[self.locationManager requestWhenInUseAuthorization];

or / and

[self.locationManager requestAlwaysAuthorization];

To avoid crashes on iOS 7 and below you can define a macro to check the OS version:

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

And then you can do:

if(IS_OS_8_OR_LATER) {
        // Use one or the other, not both. Depending on what you put in info.plist
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager requestAlwaysAuthorization];
}

Now it should work.

Macro source: iOS 8 Map Kit Obj-C Cannot Get Users Location

Upvotes: 1

Related Questions