CLLocationManager weird behavior - ios

I have a weird problem.
I have 2 classes:
BusinessVC
FavoritesVC
In both of them i show the user the current distance from him to some specific point.
In both of the classes i use the EXACT same code for that.
FavoritesVC is presented as modal view controller.
For some reason didUpdateLocations / didUpdateToLocation methods are getting called ONLY in BusinessVC and NOT in FavoritesVC.
I'm implementing CLLocationManagerDelegate delegate in both classes.
The code I'm using:
-(void)viewDidLoad {
[super viewDidLoad];
[self locatedMe];
}
-(void) locatedMe{
NSLog(#"locateMe");
_locationManager = [[CLLocationManager alloc] init];
[_locationManager setDelegate:self];
[_locationManager setDistanceFilter:kCLDistanceFilterNone]; // whenever we move
[_locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters]; // 100 m
[_locationManager startUpdatingLocation];
}
// For iOS6
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation * newLocation = [locations lastObject];
NSNumber *lat = [[NSNumber alloc] initWithDouble:newLocation.coordinate.latitude];
NSNumber *lon = [[NSNumber alloc] initWithDouble:newLocation.coordinate.longitude];
self.userLocation = [[CLLocation alloc] initWithLatitude:[lat doubleValue] longitude:[lon doubleValue]];
}
// For earlier then iOS6
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSNumber *lat = [[NSNumber alloc] initWithDouble:newLocation.coordinate.latitude];
NSNumber *lon = [[NSNumber alloc] initWithDouble:newLocation.coordinate.longitude];
self.userLocation = [[CLLocation alloc] initWithLatitude:[lat doubleValue] longitude:[lon doubleValue]];
NSLog(#"%#",self.userLocation);
}

OK! Fixed that by running the code on main thread using this code:
-(void) locateMe {
NSLog(#"locateMe");
dispatch_async(dispatch_get_main_queue(), ^{
_locationManager = [[CLLocationManager alloc] init];
[_locationManager setDelegate:self];
[_locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; // 100 m
[_locationManager startUpdatingLocation];
[_locationManager startUpdatingHeading];
});
}

Related

current location alway 00000.00, 00000.00 [duplicate]

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
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`]
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);
}
}
First go to your info.plist and right click on it and select the source code option.
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]);
}
}
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.
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
Enable Background Modes from Capabilities Tab, and choose Location Updates, see image below
Add NSLocationWhenInUseUsageDescription in Info Tab, into the plist, see image
It will start working.
Hope it helps. Cheers.
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

Why latitude and longitude is showing zero in ios 9?

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
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`]
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);
}
}
First go to your info.plist and right click on it and select the source code option.
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]);
}
}
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.
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
Enable Background Modes from Capabilities Tab, and choose Location Updates, see image below
Add NSLocationWhenInUseUsageDescription in Info Tab, into the plist, see image
It will start working.
Hope it helps. Cheers.
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

Objective-C issues with Location Manager

I am using Location Manager. Its acting very strange. I have these UILabels in place and I am looking for away to consistently update these UILabels when the coordinates change. This is what I have in place:
#implementation ViewController
{
CLLocationManager *locationManager;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
locationManager = [[CLLocationManager alloc] init];
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];
currentLocation = nil;
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
and then this:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *) newLocation
fromLocation:(CLLocation *)oldLocation
{
/*if (currentLocation == nil)
currentLocation = newLocation;
if (currentLocation != nil) {
Longitude = [NSString stringWithFormat:#"%.10f", currentLocation.coordinate.longitude];
Latitude = [NSString stringWithFormat:#"%.10f", currentLocation.coordinate.latitude];
LongitudeDouble = currentLocation.coordinate.longitude;
LatitudeDouble = currentLocation.coordinate.latitude;
}*/
currentLocation = newLocation;
Longitude = [NSString stringWithFormat:#"%.10f", currentLocation.coordinate.longitude];
Latitude = [NSString stringWithFormat:#"%.10f", currentLocation.coordinate.latitude];
LongitudeDouble = currentLocation.coordinate.longitude;
LatitudeDouble = currentLocation.coordinate.latitude;
Long.text = [NSString stringWithFormat:#"%.10f", LongitudeDouble];
Lat.text = [NSString stringWithFormat:#"%.10f", LatitudeDouble];
}
My issue is when I run the app is updates the labels sometimes, but after a bit, its stops and when I close the app and reopen it the labels do not update at all.
What Am I doing wrong?
May be you should add this line self.locationManager.distanceFilter = 0.1
And fix your code like this
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 0.1
[locationManager startUpdatingLocation];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
currentLocation = nil;
}
Try this
viewDidLoad:
locationManager =[[CLLocationManager alloc] init] ;
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];
[locationManager startUpdatingLocation];
Info.plist:
NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription
Then
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"failed to update location");
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *currentLocation=[locations lastObject];
lat=currentLocation.coordinate.latitude;
lon=currentLocation.coordinate.longitude;
NSString *strLat=[NSString stringWithFormat:#"%f",lat];
NSString *strLon=[NSString stringWithFormat:#"%f",lon];
latitude_1=[[NSMutableString alloc] initWithString:strLat];
longitude_1=[[NSMutableString alloc] initWithString:strLon];
}

CoreLocation Location does not update when heading is updating

I need to get the position and the heading. Once I run my code, I only get the heading updates, location does not update as it doesn't appear in logs.
If I disable heading updates,I get my location coordinates.
If heading updates is on I don't get location.
Has anyone had the same sort of problem?
Here's my set up routine and my methods:
locationManager = [[CLLocationManager alloc]init];
locationManager.headingFilter = 1;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
[locationManager startUpdatingHeading];
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation// fromLocation:(CLLocation *)oldLocation
{NSString *currentLatitude = [[NSString alloc] initWithFormat:#"%g", newLocation.coordinate.latitude];
NSLog(#"currentLatitude = %#", currentLatitude);
NSString *currentLongitude = [[NSString alloc] initWithFormat:#"%g", newLocation.coordinate.longitude];
NSLog(#"currentLongitude = %#", currentLongitude);
NSString *currentHorizontalAccuracy = [[NSString alloc] initWithFormat:#"%g", newLocation.horizontalAccuracy];
NSLog(#"currentHorizontalAccuracy = %#", currentHorizontalAccuracy);
NSString *currentAltitude = [[NSString alloc] initWithFormat:#"%g", newLocation.altitude];
NSLog(#"currentAltitude = %#", currentAltitude);
NSString *currentVerticalAccuracy = [[NSString alloc] initWithFormat:#"%g", newLocation.verticalAccuracy];
NSLog(#"currentVerticalAccuracy = %#", currentVerticalAccuracy);
}- (BOOL)locationManagerShouldDisplayHeadingCalibration: (CLLocationManager *)manager {
return NO;}
-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{
CLLocationDirection trueHeading = newHeading.trueHeading;}
The location has not been updating because the method has been updated in ios 6.0
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation* location = [locations lastObject];
This is how the didUpdateLocations should look like, now it takes an array.
[locations lastObject] this is the last know location in the array. From it you can get the coordinates and else.

Getting Longitude/Latitude of the User When the viewDidLoad

My purpose is to get the longitude/latitude of the user when the view is loaded and to store the values in two variables for later calculations. I don't need to track the user location and to update it, I simply need to get his/her coordinates once. My code looks like this:
- (void)viewDidLoad {
[super viewDidLoad];
// locationManager update as location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
float longitude=coordinate.longitude;
float latitude=coordinate.latitude;
NSLog(#"dLongitude : %f",longitude);
NSLog(#"dLatitude : %f", latitude);
}
In the console i keep getting this:
dLongitude : 0.000000
dLatitude : 0.000000
Can you please help me there?
To get user's location even once you need to make locationManager to start updating locations (you did that) and implement delegate method that manager calls when location is retrieved - you can't get location from location manager immediately.
If you don't want to track user location - just stop updating locations in that delegate method after location was fetched for the 1st time (and store it if you need it in future).
As soon as you call [locationManager startUpdatingLocation]; your viewDidLoad method is done. You need to implement
-(void) locationManager: (CLLocationManager *)manager didUpdateToLocation: (CLLocation *) newLocation
fromLocation: (CLLocation *) oldLocation
and
- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
which will be called by your locationManager when it gets the location, or when it fails. In both of those methods, you can call [locationManager stopUpdatingLocation].
Inside the didUpdateToLocation method, you should move all your code from viewDidLoad, starting with CLLocation *location = [locationManager location]; That's where you'll get proper values.
This worked for me
- (void)viewDidLoad {
[super viewDidLoad];
// locationManager update as location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
[locationManager stopUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
float longitude=location.coordinate.longitude;
float latitude=location.coordinate.latitude;
NSLog(#"dLongitude : %f", longitude);
NSLog(#"dLatitude : %f", latitude);
}
Try this Code
-(IBAction)Button:(id)sender
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"dLatitude : %#", latitude);
NSLog(#"dLongitude : %#",longitude);
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 40, 250, 50)];
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 80, 200, 50)];
UILabel *myLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(50, 120, 200, 100)];
myLabel.textColor = [UIColor blackColor];
myLabel1.textColor = [UIColor blackColor];
label.backgroundColor = [UIColor clearColor];
myLabel.backgroundColor = [UIColor clearColor];
myLabel1.backgroundColor = [UIColor clearColor];
[myLabel setText:latitude];
[myLabel1 setText:longitude];
label.text = #"Current Latitude And Longitude";
[self.view addSubview:label];
[self.view addSubview:myLabel];
[self.view addSubview:myLabel1];
}
if you are getting Lat lang both (0.00 ,0.00)
this may be solution for your ,
step 1:
NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription
Add these two key in Info.plist
step 2:
And than [locationManager startUpdatingLocation]; start updating
step 3:
and you need to implement
two mehthods
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation * currentLocation = [locations lastObject];
NSLog(#"Updated Lat %f",currentLocation.coordinate.longitude);
NSLog(#"Updated Lang %f",currentLocation.coordinate.latitude);
}
of CLLocationManagerDelegate in your ViewController interface.
**step 4:**
-(void)viewDidLoad
{
[super viewDidLoad];
geocoder = [[CLGeocoder alloc] init];
manager.delegate = self;
manager.desiredAccuracy = kCLLocationAccuracyBest;
[manager requestWhenInUseAuthorization];
[manager requestAlwaysAuthorization];
[manager startUpdatingLocation];
}

Resources