Getting location update after certain distance (5 m in my case) - ios

I am taking input of distance filter from user. For testing purpose I am taking it to be 5 m. But I am getting no location updates after walking 5 m. I am testing it on iPhone simulator 5s.
MainScreenController.m
#interface MainScreenController ()
#property (strong, nonatomic) IBOutlet UITextField *txtTakeDistance;
-(void)writeToTextFile : (NSArray<CLLocation *> *) location;
-(void)ShowContentlist;
#end
#implementation MainScreenController
{
//CLLocation *location;
CLLocationManager *locationManager;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
locationManager = [[CLLocationManager alloc]init];
}
- (IBAction)btnSetDistance:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; // Tried every accuracy option
locationManager.pausesLocationUpdatesAutomatically = NO;
locationManager.distanceFilter = [_txtTakeDistance.text doubleValue];
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"didFailWithError: %#", error);
UIAlertController *controller = [UIAlertController alertControllerWithTitle:#"Error" message:#"Failed to fecth current location" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
[controller addAction:okAction];
[self presentViewController:controller animated:YES completion:nil];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
CLLocation *currentLoaction;
currentLoaction = [locations lastObject];
if(locations != nil){
NSLog(#"--> : %#",locations);
[self writeToTextFile:locations];
}
[locationManager stopUpdatingLocation];
}
-(void)writeToTextFile : (NSArray<CLLocation *> *) location{
NSFileManager *fileManager = [NSFileManager defaultManager];
CLLocation *currentLocation;
currentLocation = [location lastObject];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"yyyy-MM-DD HH:mm:ss"];
NSString *timeStamp = [timeFormat stringFromDate:currentLocation.timestamp];
NSString *content = [NSString stringWithFormat:#"\n%f|%f|%#\n",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude,timeStamp];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
if ([fileManager fileExistsAtPath:documentDir]==YES) {
NSString *documentFile = [documentDir stringByAppendingPathComponent:#"log.txt"];
NSString *textFromFile = [NSString stringWithContentsOfFile:documentFile encoding:NSUTF8StringEncoding error:nil];
NSString *textToFile = [textFromFile stringByAppendingString:content];
[textToFile writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
}else{
NSLog(#"No such file");
}
}
Do correct me if I am doing it in wrong way. All the suggestions are appreciated. Thank you.

Make some change in your code like:
- (IBAction)btnSetDistance:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.pausesLocationUpdatesAutomatically = NO;
locationManager.distanceFilter =5;
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}
and most important thing is,you can not check how much distance you moved by moving mac.
you should check it on your device.

Try this code
- (IBAction)btnSetDistance:(id)sender
{
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate=self;
if (([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]))
{
[locationManager requestWhenInUseAuthorization];
}
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 5; // change it according to need
[locationManager startUpdatingLocation];
}
with this line locationManager.distanceFilter = 5; every 5 meter distance if you cover map will update
To get the updated Latitude and Longitudes use this code
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
double lat = location.coordinate.latitude;
double longi = location.coordinate.longitude;
if (abs(howRecent) < 15.0)
{
NSLog(#"%f,%f",lat,longi);
[locationManager stopUpdatingLocation];
}
}

Related

How to get location at AppDelegate, and pass the lat and long to another VC and load webview

Edited
I have managed to get a current location by using this. After that I am trying to pass lat and long as a string to another method that loads a webview. A problem is every time I load this VC, it doesn't call a following method
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
and straight away jump to the following method.
-(void)viewWillAppear:(BOOL)animated
How do I get a location first and store it an variables, pass them to another method as a string, append a string and pass it to NSURL and load a webview?
Is a lat and long retained? How do I retain it throughout my project?
What happens when I click on other tab controller and click back on this VC. Does a lat and long be refreshed again?
- (void)viewDidLoad
{
[super viewDidLoad];
geocoder = [[CLGeocoder alloc] init];
if (locationManager == nil)
{
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
locationManager.delegate = self;
[locationManager requestAlwaysAuthorization];
}
[locationManager startUpdatingLocation];
dtDate = [[NSMutableArray alloc] init];
self.currentPageIndex = 0;
self.hasAppearedFlag = NO;
}
//=== It doesn't call a following method first.
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *newLocation = [locations lastObject];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
latitude = [NSString stringWithFormat:#"%f",newLocation.coordinate.latitude];
longitude = [NSString stringWithFormat:#"%f",newLocation.coordinate.longitude];
state = placemark.administrativeArea;
country = placemark.country;
NSLog(#"This is the latitude%#", latitude);
NSLog(#"This is the longitude%#", longitude);
} else {
NSLog(#"This is the error debug%#", error.debugDescription);
}
}];
// Turn off the location manager to save power.
[manager stopUpdatingLocation];
//*** It will start loading this part below
[self setupSegmentButtons];
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/YYYY"];
NSString *dateString = [dateFormatter stringFromDate:now];
[self LoadClasses:dateString];
self.hasAppearedFlag = YES;
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(#"Cannot find the location.");
}
//=== Load webview
- (void)LoadClasses : (NSString *)sDate{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
sMemCode = [defaults objectForKey:#"txtMemCode"];
NSLog(#"Load Class This is the memCode:%#", sMemCode);
NSLog(#"Load Class This is the latitude:%#", latitude);
NSLog(#"Load Class This is the longitude:%#", longitude);
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
sURL = appDelegate.gURL;
sURL = [sURL stringByAppendingString:#"/apps/class.asp?"];
sURL = [sURL stringByAppendingString:#"memCode="];
sURL = [sURL stringByAppendingString:sMemCode];
sURL = [sURL stringByAppendingString:#"&dtpClass="];
sURL = [sURL stringByAppendingString:sDate];
sURL = [sURL stringByAppendingString:#"&lat="];
sURL = [sURL stringByAppendingString:latitude];
sURL = [sURL stringByAppendingString:#"&long="];
sURL = [sURL stringByAppendingString:longitude];
NSLog(#" The sURL to load for the current page : %# ", sURL);
NSURL *url = [NSURL URLWithString:sURL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
[webView setDelegate:(id<UIWebViewDelegate>)self];
}
Solution
I have put the `Location Delegates` to `AppDelegates`
AppDelegates.h
#import <UIKit/UIKit.h>
#import<CoreLocation/CoreLocation.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>{
CLLocationManager *locationManager;
}
#property (nonatomic, strong) NSString *slatitude;
#property (nonatomic, strong) NSString *slongitude;
#end
AppDelegates.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//--- Get current location ---
if (locationManager == nil)
{
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
locationManager.delegate = self;
//-- Pop up authrorization to use current location ---
[locationManager requestAlwaysAuthorization];
}
[locationManager startUpdatingLocation];
}
- (void)locationManager: (CLLocationManager *)manager didUpdateToLocation: (CLLocation *)newLocation fromLocation: (CLLocation *)oldLocation
{
float latitude = newLocation.coordinate.latitude;
slatitude = [NSString stringWithFormat:#"%f",latitude];
float longitude = newLocation.coordinate.longitude;
slongitude = [NSString stringWithFormat:#"%f", longitude];
NSLog(#"App:This is the latitude%#", slatitude);
NSLog(#"App:This is the longitude%#", slongitude);
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(#"Cannot find the location.");
}
In any VC,
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
latitude = appDelegate.slatitude;
longitude = appDelegate.slongitude;
I would suggest you move your code of Location Delegates to your Appdelegate File, so that it registers and keeps updating to the location delegate methods,
You can either make two property variabled from your appdelegate file and keep updating them as the delegate is called or make a getter or setter method something like this:
#interface AppDelegate : UIResponder<UILocationDelegate>{
CLLocationManager * locationManager;
}
#property (nonatomic, strong) NSString *lattitude;
#property (nonatomic, strong) NSString *longitude;
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
if (locationManager == nil)
{
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
locationManager.delegate = self;
[locationManager requestAlwaysAuthorization];
}
[locationManager startUpdatingLocation];
}
and then Implement the location delegate method here itself as
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
self.latitude = [NSString stringWithFormat:#"%f",newLocation.coordinate.latitude];
self.longitude = [NSString stringWithFormat:#"%f",newLocation.coordinate.longitude];
state = placemark.administrativeArea;
country = placemark.country;
NSLog(#"This is the latitude%#", latitude);
NSLog(#"This is the longitude%#", longitude);
}
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(#"Cannot find the location.");
}
Late you can access this from your ViewController as
- (void)viewDidAppear:(BOOL)animated {
AppDelegate* appdelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSString *lat = appdelegate.lattitude;
NSString *long = appdelegate.longitude;
}
In this manner even if you switch tab bars or change controllers, you will still have the latest locations.
Actually You are calling your method in ViewWillAppear and you are getting data in didUpdateLocations .. There is no guarntee that ViewWillappear will call after that,, better you call your method from didUpdateLocations after you recieve the data

When I fetch location of device, it always shows location set on Edit scheme of Xcode using Corelocation framework in ios

I am checking on device not on simulator and I want to fetch user's current location but it always shows location which I have set in edit scheme field from target of Xcode. I am using below code:
- (void)CurrentLocationIdentifier
{
//---- For getting current gps location
// locationManager = [CLLocationManager new];
locationManager=[[CLLocationManager alloc]init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
if(kCLAuthorizationStatusDenied)
{
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//currentLocation = [locations objectAtIndex:0];
currentLocation=[locations lastObject];
NSLog(#"location:%#",currentLocation);
[locationManager stopUpdatingLocation];
//[locationManager startUpdatingLocation];
geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
placemark = [placemarks objectAtIndex:0];
NSLog(#"\nCurrent Location Detected\n");
NSString *Country = [[NSString alloc]initWithString:placemark.ISOcountryCode];
NSString *state =[[NSString alloc]initWithString:placemark.administrativeArea];
//NSString *state =placemark.administrativeArea;
NSLog(#"%#",Country);
NSLog(#"administrativeArea>>%#",state);
self.stateLabel.text=state;
//[locationManager stopUpdatingLocation];
[[NSUserDefaults standardUserDefaults]setValue:Country forKey:#"countryISOCode"];
}
else
{
}
}];
[locationManager stopUpdatingLocation];
}
How to fetch exact country and state information of user?

How to Get only the device GPS location ios

Is there any way to get the only device gps location using the corelocation in ios.
Currently i am using the following code.
- (id)init{
if (!(self = [super init]))
return nil;
//Setup the manager
manager = [[CLLocationManager alloc] init];
if (!manager) {
return nil;
}
manager.distanceFilter = kCLDistanceFilterNone;
manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
manager.desiredAccuracy = kCLLocationAccuracyBest;
manager.delegate = self;
if ([manager respondsToSelector:#selector(pausesLocationUpdatesAutomatically)]) {
manager.pausesLocationUpdatesAutomatically = NO;
}
if ([manager respondsToSelector:#selector(requestAlwaysAuthorization)])
{
[manager requestAlwaysAuthorization];
}
[manager startUpdatingLocation];
return self;
}
You should add this code to your file. It is executed when a new location is received:
// Delegate method from the CLLocationManagerDelegate protocol.
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)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) {
// If the event is recent, do something with it.
NSLog(#"latitude %+.6f, longitude %+.6f\n",
location.coordinate.latitude,
location.coordinate.longitude);
}
}
src: Getting the Users Location - Apple

How to find current location of user in mkmapview

i want to find the current location of the user
below the code for finding coordinates from the well defined adress
hom can i find the current location of the user ..please help me
.h file
#import
#import
#interface ViewController : UIViewController<MKMapViewDelegate,CLLocationManagerDelegate>
#property(nonatomic,retain) MKMapView *myMapView;
#property (nonatomic, strong) CLGeocoder *myGeocoder;
#end
.m file
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#interface ViewController ()
{
CLLocationManager *locationManager;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.myMapView.showsUserLocation=YES;
self.view.backgroundColor=[UIColor whiteColor];
self.myMapView=[[MKMapView alloc]initWithFrame:self.view.bounds];
self.myMapView.mapType=MKMapTypeHybrid;
self.myMapView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.myMapView];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
NSString *oreillyAddress =#"india";
self.myGeocoder = [[CLGeocoder alloc] init];
[self.myGeocoder
geocodeAddressString:oreillyAddress completionHandler:^(NSArray *placemarks, NSError *error)
{
if ([placemarks count] > 0 && error == nil)
{
NSLog(#"Found %lu placemark(s).", (unsigned long)[placemarks count]);
CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0]; NSLog(#"Longitude = %f", firstPlacemark.location.coordinate.longitude); NSLog(#"Latitude = %f", firstPlacemark.location.coordinate.latitude);
}
else if ([placemarks count] == 0 &&
error == nil){ NSLog(#"Found no placemarks.");
}
else if (error != nil){
NSLog(#"An error occurred = %#", error); }
}];
// Do any additional setup after loading the view, typically from a nib.
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return YES;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
float latitude=newLocation.coordinate.latitude;
float longitude=newLocation.coordinate.longitude;
NSLog(#"%f",latitude);
NSLog(#"%f",longitude);
[locationManager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(#"error==>%#",error);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Define
CLLocationManager *lm;
CLLocation *location;
and then add the below mentioned code in your ViewDidLoad method
lm = [[CLLocationManager alloc] init];
lm.delegate = self;
lm.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
lm.distanceFilter = kCLDistanceFilterNone;
[lm startUpdatingLocation];
location = [lm location];
CLLocationCoordinate2D coordinate;
coordinate.longitude = location.coordinate.longitude;
coordinate.latitude = location.coordinate.latitude;
if((location.coordinate.longitude== 0.0 ) && (location.coordinate.latitude==0.0))
{
UIAlertView *alert2 = [[UIAlertView alloc ] initWithTitle:(#"Server Error:")message:(#"Internet Problem. Try Later !!!") delegate:nil cancelButtonTitle:nil otherButtonTitles:(#"OK"), nil];
[alert2 show];
}
else
{
coordinate = [location coordinate];
NSLog(#"Latitude of User is %f",coordinate.longitude);
NSLog(#"Longitude of User is %f",coordinate.latitude);
}
Use this
self.myMapView.showsUserLocation = YES;
If you are using the simulator, you would need to go to: Debug -> Location -> Customer. From there set your location to the desired test point.
To get user's current location in iOS 8
Add <CLLocationManagerDelegate> in .h file.
CLLocationManager *locationManager;
CLLocation *currentLocation;
locationManager = [CLLocationManager new];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse)
{
[locationManager requestAlwaysAuthorization];
}
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations lastObject];
NSLog(#"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
NSString *currentLatitude = [NSString stringWithFormat:#"%f",location.coordinate.latitude];
NSString *currentLongitude = [NSString stringWithFormat:#"%f",location.coordinate.longitude];
[locationManager stopUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status)
{
case kCLAuthorizationStatusNotDetermined:
case kCLAuthorizationStatusRestricted:
case kCLAuthorizationStatusDenied:
{
[locationManager requestAlwaysAuthorization];
}
break;
default:
{
[locationManager startUpdatingLocation];
}
break;
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"Error while getting core location : %#",[error localizedFailureReason]);
if ([error code] == kCLErrorDenied)
{
//you had denied
}
[manager stopUpdatingLocation];
}
And In your plist file Dont forget to Enter a key
NSLocationAlwaysUsageDescription
Use this:
[self.mapview setShowsUserLocation:YES];

iOS 5, waiting for location

I have this method for locate the user and then change some numbers according to the Country he's in:
- (void) localizing {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
DbOperations *dbOp = [[DbOperations alloc] init];
geoCoder = [[CLGeocoder alloc] init];
[self.geoCoder reverseGeocodeLocation: locationManager.location completionHandler:
^(NSArray *placemarks, NSError *error) {
//Get nearby address
CLPlacemark *placemark = [placemarks objectAtIndex:0];
//String to hold address
countryCode = [placemark.addressDictionary valueForKey:#"CountryCode"];
country = [placemark.addressDictionary valueForKey:#"Country"];
NSString *s2 = NSLocalizedString(#"You're currently in %#", nil);
lblLocation.text = [NSString stringWithFormat:s2, self.country];
[dbOp UsefulNumbers:self.countryCode];
NSUserDefaults *loc = [NSUserDefaults standardUserDefaults];
[loc setObject:country forKey:#"Country"];
[loc setObject:countryCode forKey:#"CountryCode"];
[loc synchronize];
}];
[locationManager stopUpdatingLocation];
NSUserDefaults *loc = [NSUserDefaults standardUserDefaults];
if ([loc objectForKey:#"Country"] == NULL) {
btnUno.enabled = NO;
btnDue.enabled = NO;
btnTre.enabled = NO;
lblLocation.text = NSLocalizedString(#"Unable to locate you", nil);
}
}
The method get called by 'viewDidLoad' method but the very first time I run the app I can't get located.
If I open up Maps, let it get the fix and then open my app, everything goes fine.
I thought that maybe I don't give enough time to the app to get a GPS fix or maybe I'm just doing it wrong.
Any suggestions?
EDIT: modified the code, not working yet.
- (id) init {
self = [super init];
if (self != nil) {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
}
return self;
}
- (void) viewDidLoad {
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
[locationManager startUpdatingLocation];
[super viewDidLoad];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
DbOperations *dbOp = [[DbOperations alloc] init];
geoCoder = [[CLGeocoder alloc] init];
[self.geoCoder reverseGeocodeLocation: locationManager.location completionHandler:
^(NSArray *placemarks, NSError *error) {
//Get nearby address
CLPlacemark *placemark = [placemarks objectAtIndex:0];
//String to hold address
countryCode = [placemark.addressDictionary valueForKey:#"CountryCode"];
country = [placemark.addressDictionary valueForKey:#"Country"];
NSString *s2 = NSLocalizedString(#"You're currently in %#", nil);
lblLocation.text = [NSString stringWithFormat:s2, self.country];
[dbOp UsefulNumbers:self.countryCode];
NSUserDefaults *loc = [NSUserDefaults standardUserDefaults];
[loc setObject:country forKey:#"Country"];
[loc setObject:countryCode forKey:#"CountryCode"];
[loc synchronize];
NSLog(#"Country: %#", country);
}];
NSUserDefaults *loc = [NSUserDefaults standardUserDefaults];
if ([loc objectForKey:#"Country"] == NULL) {
btnUno.enabled = NO;
btnDue.enabled = NO;
btnTre.enabled = NO;
lblLocation.text = NSLocalizedString(#"unable to locate", nil);
}
}
Method locationManager:didUpdateToLocation:fromLocation does not get called.
You should put your code for reverse geocoding in the delegate method for CLLocationManager:
– locationManager:didUpdateToLocation:fromLocation:
Your current setup is trying to reverse geocode a location before an update has been dispatched from the location manager.
Consider setting up your CLLocationManager in your init method and then waiting for the delegate to be called before attempting to reverse geocode anything.

Resources