CLLocationManager not getting City name - iphone

I am trying to get the current city and country using CLLocationManager with below code -
#pragma mark - Core Location Delegate Methods
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLGeocoder *reverseGeocoder = [[CLGeocoder alloc] init];
[reverseGeocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
NSLog(#"reverseGeocodeLocation:completionHandler: Completion Handler called!");
if (error){
NSLog(#"Geocode failed with error: %#", error);
return;
}
NSLog(#"Received placemarks: %#", placemarks);
CLPlacemark *myPlacemark = [placemarks objectAtIndex:0];
NSString *countryCode = myPlacemark.ISOcountryCode;
NSString *countryName = myPlacemark.country;
NSString *city1 = myPlacemark.subLocality;
NSString *city2 = myPlacemark.locality;
NSLog(#"My country code: %#, countryName: %#, city1: %#, city2: %#", countryCode, countryName, city1, city2);
}];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
CLLocationDirection th=[newHeading trueHeading];
NSLog(#"True Heading value is=%f",th);
CLLocationDirection magnetic=[newHeading magneticHeading];
NSLog(#"Magnetic Heading value is=%f",magnetic);
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSString *errorType = (error.code == kCLErrorDenied) ? NSLocalizedString(#"access_denied", #"") : NSLocalizedString(#"unknown_error", #"");
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(#"error_getting_location", #"")
message:errorType
delegate:nil
cancelButtonTitle:NSLocalizedString(#"ok", #"")
otherButtonTitles:nil];
[alert show];
}
It always gives the result with -
My country code: IN, countryName: India, city1: (null), city2: (null)
I don't know what may be the issue for this. Has anyone faced this issue that can't able to get the city name using CLLocationManager

EDITED:
- (void) getReverseGeocode
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
if(currentLatLong.count > 0)
{
CLLocationCoordinate2D myCoOrdinate;
myCoOrdinate.latitude = LatValue;
myCoOrdinate.longitude = LangValue;
CLLocation *location = [[CLLocation alloc] initWithLatitude:myCoOrdinate.latitude longitude:myCoOrdinate.longitude];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error)
{
if (error)
{
NSLog(#"failed with error: %#", error);
return;
}
if(placemarks.count > 0)
{
NSString *MyAddress = #"";
NSString *city = #"";
if([placemark.addressDictionary objectForKey:#"FormattedAddressLines"] != NULL)
MyAddress = [[placemark.addressDictionary objectForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
else
MyAddress = #"Address Not founded";
if([placemark.addressDictionary objectForKey:#"SubAdministrativeArea"] != NULL)
city = [placemark.addressDictionary objectForKey:#"SubAdministrativeArea"];
else if([placemark.addressDictionary objectForKey:#"City"] != NULL)
city = [placemark.addressDictionary objectForKey:#"City"];
else if([placemark.addressDictionary objectForKey:#"Country"] != NULL)
city = [placemark.addressDictionary objectForKey:#"Country"];
else
city = #"City Not founded";
NSLog(#"%#",city);
NSLog(#"%#", MyAddress);
}
}];
}
}

You know about the apple maps and there database for the location, better try with google places api for getting more accurate and detailed information for reverse geocoding. I have tried same for auto filling the place names, but didn't worked,so went using google places api, there is one more free api try geonames.org

in .h file
#import <CoreLocation/CoreLocation.h>
#interface ClassDemo : NSObject<NSXMLParserDelegate,CLLocationManagerDelegate>
{
BOOL got;
BOOL needParser;
NSMutableArray *currentplaceArray;
}
#property (nonatomic, retain) CLLocation *currentLocation;
#property (nonatomic, getter = isResultsLoaded) BOOL resultsLoaded;
#property (strong, nonatomic) CLLocationManager *locationManager;
#property (strong, nonatomic) CLGeocoder *geoCoder;
in .m
#synthesize locationManager,currentLocation;
- (void)viewDidLoad
{
got=NO;
needParser=YES;
currentplaceArray=[[NSMutableArray alloc]init];
//******** Location MAnager Allocation And Intialization********//
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if ([self isResultsLoaded])
{
return;
}
[self setResultsLoaded:YES];
currentLocation = newLocation;
NSLog(#"%#",currentLocation);
NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat: #"http://maps.googleapis.com/maps/api/geocode/xml?latlng=%f,%f&sensor=false",newLocation.coordinate.latitude,newLocation.coordinate.longitude]]];
[parser setDelegate:self];
[parser parse];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(#"%#",elementName);
if([elementName isEqualToString:#"formatted_address"])
{
got = YES; //got is a BOOL
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if(got&&needParser){
got=NO;
NSLog(#"the address is = %#",string);
NSArray *tempPlaceArray=[string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#",/"]];
NSLog(#"%#",tempPlaceArray);
for(int i=0; i <[tempPlaceArray count]; i++)
{
NSString *tempString=[[tempPlaceArray objectAtIndex:i]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(#"%#",tempString);
if (![currentplaceArray containsObject:tempString])
{
if ([tempString length]!=0)
{
[currentplaceArray addObject:tempString];
}
}
}
needParser=NO;
TempLocation *obj=[[TempLocation alloc]init];
obj.countryName=[currentplaceArray objectAtIndex:[currentplaceArray count]-1];
obj.stateName=[currentplaceArray objectAtIndex:[currentplaceArray count]-2];
obj.cityName=[currentplaceArray objectAtIndex:[currentplaceArray count]-3];
obj.fullAdd=string;
[[Database getDBObject]insertIntoCurrentLocationTable:obj.cityName :obj.stateName :obj.countryName:obj.fullAdd];
}
}
make a temp location class for temporary storage. And you can also save to the database as.
Enjoy Coding.

Even I noticed same issue. After many trail and error I found the problem with wifi I was using. If the signal strength is low you'll get city as nil. Try changing your connection.

Related

Passing NSString from one method to another [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I've got myself some of a newbie problem.
I got this method to determine the zip code where the iPhone is located, based on GPS coordinates. Reverse Geocoding. My method works, I know this, since it has no problem writing out the correct zip code to a label.
But I need this zip code to be stored in a string that I can use inside a method I use to compose a SMS.
Anyone can help me with that?
Tell me if an source code is necessary! (Just not currently sitting on my work comp)
Clearly i've been misunderstood, should have posted som code.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
// Reverse Geocoding
NSLog(#"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
**postalCode** = [NSString stringWithFormat:#"%#",
placemark.postalCode];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
}
Here i try to save the zip code inside the NSString named postalCode (highlighted with "**")
I try to load it again in sms composer
-(void)displaySMSComposerSheet
{
CLLocation *currentLocation;
// Reverse Geocoding
NSLog(#"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
postalCode = [NSString stringWithFormat:#"%#",
placemark.postalCode];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
picker.recipients = [NSArray arrayWithObjects:#"1220", nil];
picker.body = [NSString stringWithFormat:#"Dog %#", (placemark.)postalCode];
picker.messageComposeDelegate = self;
[self presentModalViewController:picker animated:YES];
}
only prints out in the SMS window:
Dog (null)
And i'm sure i have the coordinates, they get printed out in the output.
Hope this helps to understand the question better
#import <CoreLocation/CoreLocation.h>
#interface SomeController : UIViewController <CLLocationManagerDelegate>
#property (strong,nonatomic) CLLocationManager *locationManager;
#end
#implementation SomeController
-(void) trackUpdates
{
self.locationManager = [CLLocationManager new];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
self.locationManager.distanceFilter = 10.0f;
if ([CLLocationManager locationServicesEnabled]){
[self.locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
CLGeocoder* gcrev = [[CLGeocoder alloc] init];
[gcrev reverseGeocodeLocation:[locations lastObject]
completionHandler:^(NSArray *placemarks, NSError *error)
{
CLPlacemark* revMark = [placemarks objectAtIndex:0];
NSString *zip = [revMark.addressDictionary objectForKey:#"ZIP"];
NSLog(#"%#",zip);
// ... do something with the zip, store in an ivar, call a method, etc.
}];
}
-(void)viewDidLoad {
[super viewDidLoad];
[self trackUpdates];
}
#end

Location Services permission don't get saved iOS

I have problem with the localization API in Core Location Services. I get the promt that request permission to the location services. If I click Allow and goes to Settings I can see that my app don't have permission.
This is my code in my GeoUtility class:
CLGeocoder *reverseGeocoder = [[CLGeocoder alloc] init];
CLLocationManager *lm = [[CLLocationManager alloc] init];
[lm setPurpose:#"Need to verify your region"];
[lm startUpdatingLocation];
It's trigged by a viewController in the viewDidAppear
I also have added location-services under Required Devices Capabilites in my plist file.
Add CoreLocation.framework and MapKit.framework
And
in .h
#import <MapKit/MapKit.h>
CLLocationManager *locationManager;
CLGeocoder *geocoder;
in view did load
- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
geocoder = [[CLGeocoder alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
then
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
LongitudeLbl.text = [NSString stringWithFormat:#"%.8f",currentLocation.coordinate.longitude];
LatitudeLbl.text = [NSString stringWithFormat:#"%.8f",currentLocation.coordinate.latitude];
}
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
NSString *addresstemp2 = [[NSString alloc] init];
NSString *subThoroughfare2 = [NSString stringWithFormat:#"%#",placemark.subThoroughfare];
NSString *thoroughfare2 = [NSString stringWithFormat:#"%#",placemark.thoroughfare];
NSString *postalCode2 = [NSString stringWithFormat:#"%#",placemark.postalCode];
NSString *locality2 = [NSString stringWithFormat:#"%#",placemark.locality];
NSString *administrativeArea2 = [NSString stringWithFormat:#"%#",placemark.administrativeArea];
NSString *country2 = [NSString stringWithFormat:#"%#",placemark.country];
if (![subThoroughfare2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%#",subThoroughfare2];
}
if (![thoroughfare2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %# \n",addresstemp2,thoroughfare2];
}
if (![postalCode2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %#",addresstemp2,postalCode2];
}
if (![locality2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %# \n",addresstemp2,locality2];
}
if (![administrativeArea2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %# \n",addresstemp2,administrativeArea2];
}
if (![country2 isEqualToString:#"(null)"]) {
addresstemp2 = [NSString stringWithFormat:#"%# %#",addresstemp2,country2];
}
AddressLbl.text = [[NSString alloc] initWithString:addresstemp2];
[AddressLbl sizeToFit];
[locationManager stopUpdatingLocation];
} else {
}
} ];
}
And you also change setting in your Simulator GO TO THE setting and choose Location Service change it to ON. see down is your application name if it is off then change to ON

MKReverseGeocoder deprecated

I just saw that MKReverseGeocoder is deprecated. Question is, how do you change to CLGeocoder the easiest way? Sorry for the extremely long source code (i think you think it's pretty simple, but im new to this). This is what I got before...
StoreLocation.h
#interface StoreLocation : NSObject <MKAnnotation> {
CLLocationCoordinate2D coordinate;
}
#property (nonatomic, readwrite) CLLocationCoordinate2D coordinate;
#property (nonatomic, readwrite) NSString *subtitle;
-(id)initWithCoordinate:(CLLocationCoordinate2D) coordinate;
- (NSString *)subtitle;
- (NSString *)title;
#end
StoreLocation.m
#implementation StoreLocation
#synthesize coordinate,subtitle;
-(NSString *)subtitle{
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
if ([userDef boolForKey:#"SavedAddress"]) {
NSString *savedAddress = [[NSUserDefaults standardUserDefaults] stringForKey:#"SavedAddress"];
return savedAddress;
}
else {
return subtitle;
}
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) coor{
self.coordinate=coor;
return self;
}
- (void)setCoordinate:(CLLocationCoordinate2D)coor {
MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:coor];
geocoder.delegate = self;
coordinate = coor;
[geocoder start];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
NSLog(#"fail %#", error);
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
self.subtitle = [placemark.addressDictionary valueForKey:#"Street"];
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
[userDef setValue:subtitle forKey:#"SavedAddress"];
}
MapViewController.m
-(void) locationManager: (CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation*)oldLocation{
MKGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:location];
[geocoder start];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark{
NSString *streetAddress = [NSString stringWithFormat:#"%#, %#",
[placemark.addressDictionary objectForKey:(NSString *)kABPersonAddressStreetKey],
[placemark.addressDictionary objectForKey:(NSString *)kABPersonAddressCityKey]];
mapView.userLocation.subtitle = streetAddress;
}
-(IBAction)storeLocation {
StoreLocation *position=[[StoreLocation alloc] initWithCoordinate:location]; [mapView addAnnotation:position]; }
- (MKAnnotationView *)mapView:(MKMapView *)mapview
viewForAnnotation:(id <MKAnnotation>)dropPin
{
if ([dropPin isKindOfClass:MKUserLocation.class])
{
return nil;
}
MKPinAnnotationView *pinView = (MKPinAnnotationView*)[mapview dequeueReusableAnnotationViewWithIdentifier:#"annot"];
if (!pinView)
{
pinView = [[MKPinAnnotationView alloc] initWithAnnotation:dropPin reuseIdentifier:#"annot"];
pinView.canShowCallout = YES;
}
else {
pinView.annotation = dropPin;
}
return pinView;
}
Thanks a thousand times!
Maybe like this?
MKReverseGeocoder is deprecated in all firmwares after iOS4. This just means that it is now obsolete and frowned upon to be using the outdated class. Use CLGeocoder instead, like so:
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:self.locationManager.location // You can pass aLocation here instead
completionHandler:^(NSArray *placemarks, NSError *error) {
dispatch_async(dispatch_get_main_queue(),^ {
// do stuff with placemarks on the main thread
if (placemarks.count == 1) {
CLPlacemark *place = [placemarks objectAtIndex:0];
NSString *zipString = [place.addressDictionary valueForKey:#"ZIP"];
[self performSelectorInBackground:#selector(showWeatherFor:) withObject:zipString];
}
});
}];
If you want to reverse geocode a hardcoded pair of coordinates perse --
Initialize a CLLocation location with your latitude and longitude:
CLLocation *aLocation = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
I also want to point out that you can still use MKReverseGeocoder. It may be removed with future iOS updates though.

How to get device location name in iPhone?

Currently i am working in iPhone application, Using CLLocationManager to get Latitude and Longitude values fine.
I didn't know this? How to get the device location (Address) name from this latitude and longitude value? please help me
Thanks in Advance
I tried this:
- (void)viewDidLoad
{
[super viewDidLoad];
LocationManager = [[CLLocationManager alloc]init];
LocationManager.delegate=self;
LocationManager.desiredAccuracy = kCLLocationAccuracyBest;
[LocationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSString * latitude = [[[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.latitude]autorelease];
NSString * longitude = [[[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.longitude]autorelease];
[LocationManager stopUpdatingLocation];
NSLog(#"latitude:%#",latitude);
NSLog(#"longitude:%#",longitude);
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[manager stopUpdatingLocation];
lati = [[NSString alloc] initWithFormat:#"%+.6f", newLocation.coordinate.latitude];
NSLog(#"address:%#",lati);
longi = [[NSString alloc] initWithFormat:#"%+.6f", newLocation.coordinate.longitude];
NSLog(#"address:%#",longi);
[geoCoder reverseGeocodeLocation: newLocation completionHandler: ^(NSArray *placemarks, NSError *error)
{
//Get nearby address
CLPlacemark *placemark = [placemarks objectAtIndex:0];
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
//Print the location to console
NSLog(#"I am currently at %#",locatedAt);
address = [[NSString alloc]initWithString:locatedAt];
NSLog(#"address:%#",address);
}];
}
CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:32.00 longitude:21.322];
[ceo reverseGeocodeLocation: loc completionHandler:
^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"placemark %#",placemark);
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSLog(#"addressDictionary %#", placemark.addressDictionary);
NSLog(#"placemark %#",placemark.region);
NSLog(#"placemark %#",placemark.country); // Give Country Name
NSLog(#"placemark %#",placemark.locality); // Extract the city name
NSLog(#"location %#",placemark.name);
NSLog(#"location %#",placemark.ocean);
NSLog(#"location %#",placemark.postalCode);
NSLog(#"location %#",placemark.subLocality);
NSLog(#"location %#",placemark.location);
//Print the location to console
NSLog(#"I am currently at %#",locatedAt);
}];
You have ta make some reverse location. You're lucky : Apple provides a class to do that.
See CLGeocoder (for iOS >= 5.0) or MKReverseGeocoder (for iOS < 5.0)
You can use Google Maps API for this (works on any iOS):
NSString *req = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?latlng=%.5f,%.5f&sensor=false&language=da", location.latitude, location.longitude];
NSString *resultString = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
Then you can parse this response to NSDictionary using Any JSON library (SBJSON in this case):
SBJSON *jsonObject = [[SBJSON alloc] init];
NSError *error = nil;
NSDictionary *response = [jsonObject objectWithString:resultString error:&error];
[jsonObject release];
Extracting address:
if (error) {
NSLog(#"Error parsing response string to NSObject: %#",[error localizedDescription]);
}else{
NSString *status = [response valueForKey:#"status"];
if ([status isEqualToString:#"OK"]) {
NSArray *results = [response objectForKey:#"results"];
int count = [results count];
//NSSLog(#"Matches: %i", count);
if (count > 0) {
NSDictionary *result = [results objectAtIndex:0];
NSString *address = [result valueForKey:#"formatted_address"];
}
}
}
You have to create a CLLocation object and pass that on to reverseGeoCoder.
Before iOS 5.0 we have MKReverse Geo-coder class to find this..Now it is deprecated..
We have to use CLGeocoder class in Core Location Framework

CLGeocoder only shows nearest apple store?

Is CLGeocoder just that coarse right now? I was expecting something relatively close to a street address. I'm testing on the 5.1 simulator and using ARC. I made a quick test project right now with the following if that helps:
- (IBAction)getLocationPressed {
if ([CLLocationManager locationServicesEnabled] &&
[CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized) {
[self.geoCoder reverseGeocodeLocation:self.locationManager.location completionHandler:
^(NSArray *placemarks, NSError *error) {
// Note: there is NO guarantee that the CLGeocodeCompletionHandler will be invoked on the main thread
dispatch_async(dispatch_get_main_queue(),^ {
NSLog(#"placemarks count: %d", [placemarks count]);
CLPlacemark *placemark = [placemarks objectAtIndex:0];
// Note: if a poor location is specified, there may be multiple placemarks for the given location
NSString *currentAddress = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSLog(#"I am currently at %#", currentAddress);
self.locationLabel.text = currentAddress;
});
}];
}
}
#pragma mark - CLLocationManager Delegate Methods
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
// do something...
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
if (error.code == kCLErrorDenied) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"this can not work without location services enabled"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
#pragma mark - Lifecycle Methods
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager.delegate = self;
self.locationManager.purpose = REASON_FOR_USING_LOCATION;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;//kCLLocationAccuracyNearestTenMeters;
[self.locationManager startUpdatingLocation];
}
Thanks
YESSSS! It turns out that I just wasn't enabling location in the simulator. It actually works if I test it on my device. Here's an example of with the full .m file if it helps anyone. I've set up a couple labels and a rounded rect button that you'll see from the code:
#define REASON_FOR_USING_LOCATION (#"to find the closest widget")
#interface ViewController () <CLLocationManagerDelegate>
#property (weak, nonatomic) IBOutlet UILabel *locationLabel;
#property (strong, nonatomic) CLLocationManager *locationManager;
#property (strong, nonatomic) CLGeocoder *geoCoder;
#end
#implementation ViewController
#pragma mark - Getters/Setters
#synthesize locationLabel = _locationLabel;
#synthesize locationManager = _locationManager;
#synthesize geoCoder = _geoCoder;
// lazily instantiate as required
- (CLGeocoder *)geoCoder {
if (!_geoCoder) _geoCoder = [CLGeocoder new];
return _geoCoder;
}
- (CLLocationManager *)locationManager {
if (!_locationManager) _locationManager = [CLLocationManager new];
return _locationManager;
}
#pragma mark - Target/Action Methods
- (IBAction)clearLocationPressed {
self.locationLabel.text = #"";
}
- (IBAction)getLocationPressed {
if ([CLLocationManager locationServicesEnabled] &&
[CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized) {
[self.geoCoder reverseGeocodeLocation:self.locationManager.location completionHandler:
^(NSArray *placemarks, NSError *error) {
// Note: there is NO guarantee that the CLGeocodeCompletionHandler will be invoked on the main thread
dispatch_async(dispatch_get_main_queue(),^ {
NSLog(#"placemarks count: %d", [placemarks count]);
CLPlacemark *placemark = [placemarks objectAtIndex:0];
// Note: if a poor location is specified, there may be multiple placemarks for the given location
NSString *currentAddress = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSLog(#"I am currently at %#", currentAddress);
self.locationLabel.text = currentAddress;
});
}];
}
}
#pragma mark - CLLocationManager Delegate Methods
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
// do something...
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
if (error.code == kCLErrorDenied) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"this can not work without location services enabled"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
#pragma mark - Lifecycle Methods
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager.delegate = self;
self.locationManager.purpose = REASON_FOR_USING_LOCATION;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;//kCLLocationAccuracyNearestTenMeters;
[self.locationManager startUpdatingLocation];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
- (void)viewDidUnload {
[self setLocationLabel:nil];
[self setLocationManager:nil];
[self setGeoCoder:nil];
[super viewDidUnload];
}
#end