14

I am trying to get the user's current location using the Core Location Framework in Xcode 6.3.1, I did following things:

  1. Added Core Location Framework under Target-> General-> Linked Frameworks & Libraries
  2. My ViewController.h file is as shown below,

    #import <UIKit/UIKit.h>
    #import <CoreLocation/CoreLocation.h>
    
    @interface ViewController : UIViewController<CLLocationManagerDelegate>
    @property (weak, nonatomic) IBOutlet UILabel *lblLatitude;
    @property (weak, nonatomic) IBOutlet UILabel *lblLongitude;
    @property (weak, nonatomic) IBOutlet UILabel *lblAddress;
    @property (strong, nonatomic) CLLocationManager *locationManager;
    
    @end
    
  3. My ViewController.m file is as shown below,

    - (void)viewDidLoad
    {
    
    [super viewDidLoad];
    self.locationManager = [[CLLocationManager alloc] init];
    
    self.locationManager.delegate = self;
    if(IS_OS_8_OR_LATER){
        NSUInteger code = [CLLocationManager authorizationStatus];
        if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) {
        if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]){
            [self.locationManager requestAlwaysAuthorization];
        } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) {
            [self.locationManager  requestWhenInUseAuthorization];
        } else {
            NSLog(@"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
        }
    }
    }
    [self.locationManager startUpdatingLocation];
    }
    
    #pragma mark - CLLocationManagerDelegate
    
    - (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) {
            lblLatitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
            lblLongitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
        }
    }
    @end
    

I had also added the following keys in my info.plist file

  • NSLocationWhenInUseUsageDescription
  • NSLocationAlwaysUsageDescription

plist image

Checked everything given here, here, here, here, and a lot more list

So, is anyone having a solution for this issue, kindly help. Have lost my mind searching for this for the whole day.

Community
  • 1
  • 1
iYoung
  • 3,596
  • 3
  • 32
  • 59
  • The values for those usage description is empty. Are you sure you've put them in? Also why do you have two usage description? – Vinh Nguyen May 17 '15 at 15:29
  • @VinhNguyen I had tried by putting values in that too, but that does not have any affect, & by keeping only NSLocationAlwaysUsageDescription then also that doesn't work for me. Tried that too... – iYoung May 17 '15 at 15:32
  • Try remove the if block `if (code == kCLAuthorizationStatusNotDetermined &&....` and simply call either `requestAlwaysAuthorization` or `requestWhenInUseAuthorization` on your `locationManager` instance – Vinh Nguyen May 17 '15 at 15:43
  • Tried, but still delegate in not called, not even got the prompt message. – iYoung May 17 '15 at 15:46
  • What's in your `IS_OS_8_OR_LATER` macro? Try remove that too. – Vinh Nguyen May 17 '15 at 15:52
  • It was to check the device version `#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)`, removed that too but no difference, same result – iYoung May 17 '15 at 15:56
  • Sounds weird, but try delete the app and run again. And, best is to set breakpoints to see if something is missing. – Vinh Nguyen May 17 '15 at 15:58
  • Check out http://nshipster.com/core-location-in-ios-8/ if you're still stuck. – Vinh Nguyen May 17 '15 at 17:51
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/78060/discussion-between-rajat-deep-singh-and-vinh-nguyen). – iYoung May 18 '15 at 05:36

1 Answers1

6

Yeah! Got the solution, Here is my whole code & things added to make it working. Special thanks to @MBarton for his great help. Also Thanks to @ Vinh Nguyen for investing his precious time in solving my issue.

Added Core Location Framework under Target-> General-> Linked Frameworks & Libraries

Added in .plist file

NSLocationAlwaysUsageDescription

See Screenshot:

plist screenshot

In my ViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>

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

@interface ViewController : UIViewController  <MKMapViewDelegate,  CLLocationManagerDelegate>
{
    __weak IBOutlet UINavigationItem *navigationItem;
}

 @property (weak, nonatomic) IBOutlet MKMapView *mapView;
 @property(nonatomic, retain) CLLocationManager *locationManager;

@end

Then in ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize mapView;

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

    [self setUpMap];
}

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

-(void)setUpMap
{
    mapView.delegate = self;
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
   // if(IS_OS_8_OR_LATER) {
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) { 
        // Use one or the other, not both. Depending on what you put in info.plist
        [self.locationManager requestAlwaysAuthorization];
    }
#endif
    [self.locationManager startUpdatingLocation];

    mapView.showsUserLocation = YES;
    [mapView setMapType:MKMapTypeStandard];
    [mapView setZoomEnabled:YES];
    [mapView setScrollEnabled:YES];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];

    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [self.locationManager startUpdatingLocation];
    NSLog(@"%@", [self deviceLocation]);

    //View Area
    MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } };
    region.center.latitude = self.locationManager.location.coordinate.latitude;
    region.center.longitude = self.locationManager.location.coordinate.longitude;
    region.span.longitudeDelta = 0.005f;
    region.span.longitudeDelta = 0.005f;
    [mapView setRegion:region animated:YES];

}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}
- (NSString *)deviceLocation {
    return [NSString stringWithFormat:@"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
}

Ufff...! Got the solution after fighting with many codes since last 5 days...

iYoung
  • 3,596
  • 3
  • 32
  • 59
  • Do not use `IS_OS_8_OR_LATER`. There are proper ways to check if an API is available or not. – rmaddy Apr 28 '16 at 17:38
  • @rmaddy Updated my code, kindly review & provide your valuable suggestions. Thanks for letting me know about this. – iYoung Apr 29 '16 at 02:47
  • That's better. I'd completely remove all references to those macros from your answer. – rmaddy Apr 29 '16 at 02:54