Objective-C issues with Location Manager - ios

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];
}

Related

IOS CLLocationManager is returning latitude: 0.000000 longitude: 0.000000

I have been trying to get the current location IOS8 and following thread Location Services not working in iOS 8 but getting the 00.00,00.00 instead current location. Any suggestion on where I am doing wrong.
ViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
#interface ViewController : UIViewController <CLLocationManagerDelegate>
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
NSLog(#"%#", [self deviceLocation]);
CLLocation *location = [self.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(#"%#",latitude);
NSLog(#"%#",longitude);
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)setUpMap
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
}
-(NSString *)deviceLocation
{
return [NSString stringWithFormat:#"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[manager stopUpdatingLocation];
CLLocationCoordinate2D coordinate_currentlocation = [newLocation coordinate];
float latitude_current = newLocation.coordinate.latitude;
float longitude_current = newLocation.coordinate.longitude;
NSLog(#"%f",latitude_current);
NSLog(#"%f",longitude_current);
NSLog(#"Current latitude :%f",coordinate_currentlocation.latitude);
NSLog(#"Current longitude :%f",coordinate_currentlocation.longitude);
}
#end
I have also added the following key in my info.plist
<key>NSLocationAlwaysUsageDescription</key>
<string>Your location is needed for this app.</string>
Add this string in InfoPlist.strings files
1) NSLocationWhenInUseUsageDescription
2) NSLocationAlwaysUsageDescription
Try this code
locationManagerApp=[[CLLocationManager alloc] init];
locationManagerApp.delegate = self;
locationManagerApp.distanceFilter = kCLDistanceFilterNone;
locationManagerApp.desiredAccuracy = kCLLocationAccuracyHundredMeters;
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
[locationManagerApp requestAlwaysAuthorization];
}
[locationManagerApp startUpdatingLocation];
CLLocation *location1 = [locationManagerApp location];
CLLocationCoordinate2D coordinate = [location1 coordinate];
self.latValue= [NSString stringWithFormat:#"%f", coordinate.latitude];
self.longValue = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"Latitude = %#", self.latValue);
NSLog(#"Longitude = %#", self.longValue);
And run your project in device. If you run project in simulator then not get lat/ long.
get the current location on simulator (select any one location).
There was a mistake in code, The function which actually checking the authorization never called. I moved my all the code to viewDidLoad as below and it worked. Thank you for looking into this.
- (void)viewDidLoad {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER)
{
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
[self.locationManager startUpdatingLocation];
NSLog(#"%#", [self deviceLocation]);
[super viewDidLoad];
}

Testing a fake current location on iOS Simulater is not working

I have been trying to fake my location in the iOS simulator but the methods I have been reading about are not working. I have used the debugger to set my fake location, and have made a custom location in Debug->Location->Custom Location, yet I still log 0.000 0.000 for lat and long.
I'm using this code to find current location.
- (IBAction)currentLocationButtonPressed:(UIButton *)sender
{
//Search for pubs and bars in current location.
//Push to tableViewController
NSLog(#"current location Pressed.");
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyBest; // Best accuracy
[locationManager startUpdatingLocation];
NSLog(#"%#",[self deviceLocation]);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSLog(#"Latitude: %f Longitude: %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
}
}
- (NSString *)deviceLocation {
return [NSString stringWithFormat:#"latitude: %f longitude: %f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
}
The delegate is set and I am requesting authorization.
- (void)viewDidLoad {
[super viewDidLoad];
searchLocationTextField.delegate = self;
locationManager.delegate = self;
locationManager = [[CLLocationManager alloc]init];
[locationManager requestWhenInUseAuthorization]; // For foreground access
[locationManager requestAlwaysAuthorization]; // For background access
}
Set locationManager delegate to after allocating it.
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
locationManager:didUpdateToLocation:fromLocation: delegate method is deprecated, use locationManager:didUpdateLocations: instead.
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *currentLocation = [locations lastObject];
NSLog(#"Latitude: %f Longitude: %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
}

Gps Location Services are not working in iOS 8

my program is working fine in iOS7 but not iOS8..
locationManager is object of CLLocationManager here.
In starting this code is working fine in iOS7,i can not understand why this happen to me.
- (void)getCurrentLocation{
locationManager = [[CLLocationManager alloc] init];
geocoder = [[CLGeocoder alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
if (status == kCLAuthorizationStatusAuthorized) {
NSUserDefaults *notify = [NSUserDefaults standardUserDefaults];
[notify setObject:#"GPS" forKey:#"Notification"];
[notify synchronize];
appDelegate = (JobDiagnosisAppDelegate *)[[UIApplication sharedApplication] delegate];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
[appDelegate showIndicator];
[notify setObject:nil forKey:#"Notification"];
[notify synchronize];
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
[appDelegate.objActivityAlertView close];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
appDelegate = (JobDiagnosisAppDelegate *)[[UIApplication sharedApplication] delegate];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
[appDelegate showIndicator];
[self callWebserviceLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
NSLog(#"Resolving the Address");
[geocoder reverseGeocodeLocation: locationManager.location completionHandler:
^(NSArray *placemarks, NSError *error) {
//Get address
CLPlacemark *placemark = [placemarks objectAtIndex:0];
//String to address
NSString *locatedaddress =[placemark valueForKey:#"administrativeArea"] ;
//Print the location in the console
NSLog(#"Currently address is: %#",locatedaddress);
NSUserDefaults *notifyLocation = [NSUserDefaults standardUserDefaults];
[notifyLocation setObject:locatedaddress forKey:#"notifyLocation"];
[notifyLocation synchronize];
locationManager.delegate = nil;
[self callWebserviceUnRegistered];
}];
[locationManager stopUpdatingLocation];
}
please help to solve this location problem.I am new in location services.
thanks in advance!!
You Need to implement
[locationManager requestWhenInUseAuthorization];or
[locationManager requestAlwaysAuthorization];
If you do not make either of two request , iOS will ignore startUpdateLocation request.
Also,
Include NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key in Info.plist depending upon which permission you are asking for. This string will be diaplayed by iOS to user so the user can get excat idea why does our app needs permission.
So change your methood to
- (void)getCurrentLocation{
locationManager = [[CLLocationManager alloc] init];
geocoder = [[CLGeocoder alloc] init];
locationManager.delegate = self;
[locationManager requestWhenInUseAuthorization];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
And aslo add required key in info.plist.
Hope this helps.
First, don't forget, with IOS 8 you need to add NSLocationWhenInUseUsageDescription property to the info.plist file in order to prompt the alert to get the user's permission and use[locationManager requestWhenInUseAuthorization] plus [locationManager requestAlwaysAuthorization];
_locationManager = [CLLocationManager new];
if(SYSTEM_IS_OS_8_OR_LATER) {
[_locationManager requestWhenInUseAuthorization];
[_locationManager requestAlwaysAuthorization];
}
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager startUpdatingLocation];
and in your didUpdateLocations
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
_currentLocation = [locations objectAtIndex:0];
//do your stuff with the location
}

CLLocationManager weird behavior

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];
});
}

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