Objective-C: Finding User Location (Not on a Map) - ios

I am trying to make my app find a user's location in an address-like form (located after the "Reverse Geocoding" comment). Below is my code:
- (IBAction)getuserlocation:(id) sender{
//Getting Location
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
NSLog(address);
}
#pragma mark - CLLocationManagerDelegate
- (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) {
longitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
latitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
// Stop Location Manager
[locationManager stopUpdatingLocation];
// 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];
address = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
}
My issue is that the compiler only prints out "(null)". (The line where I do this is located in the "getuserlocation" IBAction.) I'm not sure why this is. I've tested the app on an actual iPhone 6 Plus, which unlike the simulator, has access to location services.
If anyone would be able to point out where the error/problem in my code is, causing it to print out null, I would greatly appreciate it. Thanks in advance to all who reply.
***BTW: The following lines are in my viewDidLoad section:
locationManager = [[CLLocationManager alloc] init];
geocoder = [[CLGeocoder alloc] init];

You are logging address long before you get a location and convert it to an address.
Move the NSLog(address); to just after where you actually assign a value to address.
BTW - it should be more like: NSLog(#"Address: %#, address);.

Related

Why use CLGeocoder with an array of "placemarks"?

When trying to use CLGeocoder, I got this example from an online tutorial:
https://www.appcoda.com/how-to-get-current-location-iphone-user/
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
latitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
// 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];
addressLabel.text = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
}
However, I don't quite understand why it takes an array of "placemarks" in the completion handler part and why we should use the last object of "placemarks" (I also see people using the first object?).
I've read through the apple document but didn't find any good explanation in terms of use:
https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLGeocoder_class/
You are reverse-geocoding a lat/long. It might yield more than one address. If you get more than one and don't care which one you use, it's just as valid to extract the first or last placemark object in the array.
(You'll probably only get one match most of the time, in which case the first and last element are the same thing.)

Not getting a correct address from Latitude & Longitude

I want to get the true postal address from the Latitude & Longitude, however is not working well. Maybe I am note using the right APIs or etc.
For example I have the following code
var location = CLLocation(latitude:currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
print(location)
if error != nil {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0] as! CLPlacemark
street = String(pm.thoroughfare!)
city = String(pm.locality!)
state = String(pm.administrativeArea!)
print(pm.locality)
print(pm.administrativeArea)
print(pm.thoroughfare)
self.utility.setMyLocation(dName, longitude: long, latitude: lat, street: street, city: city, state: state)
locManager.stopUpdatingLocation()
}
else {
print("Problem with the data received from geocoder")
}
})
However I am not getting the true address. For example let say if that long and lat address is
123 East Street
I get something like only East Street (with no number) or near by road.
What do I need to do inorder to get the real address?
Im not sure if this is what your looking for but its what i currently use to get a nice readable address. I also send these values to my Application delegate for referencing later if i need them. I don't have it written in Swift however just in Objective C. :/ But i think the key is reverseGeocodeLocation
#pragma mark - location Manager update and FUNCTIONS
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"%s Failed with Error: %#", __PRETTY_FUNCTION__, error);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(#"%s Update to Location: %#", __PRETTY_FUNCTION__, newLocation);
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSString *longitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
NSString *latitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
NSLog(#"Longitude: %#", longitude);
NSLog(#"Latitude: %#", latitude);
// Set current values to the AppDelegate for refrencing
appDelegate.locationDetailLon = longitude;
appDelegate.locationDetailLat = latitude;
}
// Stop Location Manager to save power
[locationManager stopUpdatingLocation];
// Reverse Geocoding
NSLog(#"Translating and getting 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];
NSString *address = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
NSLog(#"Address:\n%#", address);
// Set current values to the AppDelegate for refrencing
appDelegate.locationDetailState = placemark.administrativeArea;
appDelegate.locationDetailCountry = placemark.country;
appDelegate.locationDetailCity = placemark.locality;
appDelegate.locationDetailPostCode = placemark.postalCode;
} else {
NSLog(#"%s ERROR: %#", __PRETTY_FUNCTION__, error.debugDescription);
}
} ];
}

User's location using corelocationframework is not working without wifi

Hi i am beginner in Ios and in my project i am using CLLocationManager for getting current location but when i turn off "Wifi" and i Enable the GPS service but current location is not displaying with out internet it's showing error message how can we get current location using GPs with out internet (i am using i pad for testing this app)
my code is below:
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
if([locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]){
NSUInteger code = [CLLocationManager authorizationStatus];
if (code == kCLAuthorizationStatusNotDetermined && ([locationManager respondsToSelector:#selector(requestAlwaysAuthorization)] || [locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])) {
if([[NSBundle mainBundle] objectForInfoDictionaryKey:#"NSLocationAlwaysUsageDescription"]){
[locationManager requestAlwaysAuthorization];
[locationManager setDistanceFilter:10.0f];
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
}
else if([[NSBundle mainBundle] objectForInfoDictionaryKey:#"NSLocationWhenInUseUsageDescription"]) {
[locationManager requestWhenInUseAuthorization];
[locationManager setDistanceFilter:10.0f];
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
} else {
NSLog(#"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
}
}
}
[locationManager startUpdatingLocation];
}
- (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) {
longitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
latitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
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];
adressLabel.text = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
}
else {
NSLog(#"%#", error.debugDescription);
}
} ];
}
Add a line in the app's info.plist file, that says: NSLocationWhenInUseUsageDescription, it should fix your problem.

Location Issue in iPhone Device

I want to detecting user's current location in my app.I am using objective c.It's working fine in simulator but while testing on device below error comes.
didFailWithError: Error Domain=kCLErrorDomain Code=0 "The operation couldn’t be completed. (kCLErrorDomain error 0.)"
Please Help me to solve this issue.I am using Lat long value for find out place mark in my application.
if(version<8.0)
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
else
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
// Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}
Here are delegate method
- (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) {
NSString *longitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
NSString *latitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation: locationManager.location completionHandler:
^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSString *placemark_str = [placemark locality];
subAdminArea.text=placemark.subAdministrativeArea;
NSString *are_str = [placemark subLocality];
subAdminArea.text=placemark.subAdministrativeArea;
NSString *location_str=[NSString stringWithFormat:#"%#,%#",are_str,placemark_str];
[[NSUserDefaults standardUserDefaults]setValue:location_str forKey:#"Location"];
NSLog(#"place mark str: %#",placemark_str);
}];
}}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
NSLog(#"%#", [locations lastObject]);
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation: [locations lastObject] completionHandler:
^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSString *placemark_str = [placemark locality];
NSString *are_str = [placemark subLocality];
NSString *location_str=[NSString stringWithFormat:#"%#,%#",are_str,placemark_str];
[[NSUserDefaults standardUserDefaults]setValue:location_str forKey:#"Location"];
}];}
- (void)requestAlwaysAuthorization{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
// If the status is denied or only granted for when in use, display an alert
if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
NSString *title;
title = (status == kCLAuthorizationStatusDenied) ? #"Location services are off" : #"Background location is not enabled";
NSString *message = #"To use background location you must turn on 'Always' in the Location Services Settings";
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Settings", nil];
[alertView show];
}
// The user has not enabled any location services. Request background authorization.
else if (status == kCLAuthorizationStatusNotDetermined) {
[locationManager requestAlwaysAuthorization];
}}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1) {
// Send the user to the Settings for this app
NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:settingsURL];
}}
I have also update my plist file with NSLocationAlwaysUsageDescription->String & NSLocationWhenInUseUsageDescription -> String.
Thank You.
1) check that you actually have a valid WiFi and 3G connection
if you do then
2) go to settings and reset your location services
3) then reset your network settings

Core Location Not Finding Current Location

Current location is not being found on initial load or resume after multi-tasking. This is what I have:
ViewController.h
#interface ViewController : UIViewController <CLLocationManagerDelegate, ADBannerViewDelegate, BEMSimpleLineGraphDelegate>
ViewController.m
#interface ViewController (){
CLLocationManager *locationManager;
CLLocation *location;
CLLocationCoordinate2D coordinate;
int timeofday;
NSString *cityName;
NSMutableArray *ArrayOfValues;
}
#end
Further down:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(updateLabels) name:UIApplicationWillEnterForegroundNotification object:nil];
// set up coordinates for current location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = (id)self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
location = [locationManager location];
}
Then my update labels method (which has other code that updates my view below this):
- (void)updateLabels
{
CLLocationCoordinate2D currentLocation = [location coordinate];
if (currentLocation.latitude) {
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:location
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error){
NSLog(#"Geocode failed with error: %#", error);
return;
}
CLPlacemark *placemark = [placemarks objectAtIndex:0];
cityName = [NSString stringWithFormat:#"%# is currently",placemark.locality];
}];
[self updateLabels];
} else {
NSLog(#"Could not find the location.");
}
}
And here are the 2 delegate methods for cclocationmanager:
#pragma mark - CLLocationManagerDelegate
- (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;
[self updateLabels];
[locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error){
NSLog(#"Geocode failed with error: %#", error);
return;
}
// CLPlacemark *placemark = [placemarks objectAtIndex:0];
}];
}
Try removing the call to stopUpdatingLocation. Also un-comment the log statement in didUpdateToLocation.
Be aware that the method locationManager:didUpdateToLocation:fromLocation: is deprecated in iOS 6. It might not even be called in iOS 7. You should be using `locationManager:didUpdateLocations:' instead.
Your call to updateLabels is using the value set in the member variable location. However your didUpdateToLocation method is not setting this value.
Put some breakpoints in your code and see where it triggers.
Note, for a weather application you do not need kCLLocationAccuracyBest, that takes way more time than coarser settings. You'll get your answer much quicker.
You are setting location, which I assume is a class level iVar, in ViewDidLoad.
location = [locationManager location];
I expect that the location manager at that point has no location.
Then, in the delegate call, you are updating a method level iVar :
CLLocation *currentLocation = newLocation;
This variable is never used, that I can see. Your updateLabels call once again refers to location which has never been updated.
CLLocationCoordinate2D currentLocation = [location coordinate];
Change the delegate to:
location = newLocation;
As #Duncan C stated, the delegate method you are using is deprecated, you should really be using locationManager:didUpdateLocations: in which case you would use:
location = [locations lastObject];

Resources