Sunday, 2 November 2014

How to fix CLLocationManager location updates issue in iOS 8

It was  time consuming issue for me to  fix CLLocationManager location update issue in iOS 8.x, I was too much worried, why my code is not working in iOS 8 neither asking for user permission nor the location update delegate. 

CLLocationManager fails to work with  [self.locationManager startUpdatingLocation]. CLLocationManager not working for updating location updates. Its neither giving any error nor warning so it is more complex to figure out why this is not working.
Even Application did not ask for location related permission. So you might get irritate, don’t worry here the solution.

What are extra updates for iOS 8:
There are two more things need to be add to working with location.
1- Add one or both below keys to (app-name)info .plist file:

* NSLocationAlwaysUsageDescription
* NSLocationWhenInUseUsageDescription

Above keys take a string as description of why your app need location services. You may enter a string like “To Find out your location”
Note: iOS will not ask an user for permission to use their location until you have given a reason as why you are requesting it.

2- Request authorization for related location method, i.e WhenInUSe or Always. Use one of below method calls.

[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];

WhenInUseAuthorization:  It allows the application to get location updates when the application is in foreground state and not in other state.
requestAlwaysAuthorization: It allows the application to get location updates in both when the application  is in the foreground and or in the background.
Below is the sample code for help.

Before using this code make sure you already added NSLocationWhenInUseUsageDescription in the  (app-name)info .plist  file.

- (void)viewDidLoad
    [super viewDidLoad];
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    // Check for iOS 8 Vs earlier version like iOS7.Otherwise code will
   // crash on ios 7
    if ([self.locationManager respondsToSelector:@selector
                       (requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager startUpdatingLocation];

// CLLocationManager Delegate Methods
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:
(NSArray *)locations
    NSLog(@"location info object=%@", [locations lastObject]);
I hope You will enjoyed this post and if you any suggestion or feedback
 your most welcome

No comments:

Post a comment