I'm trying to get the city name of my location, I use this code:
- (void)viewDidLoad
{
[super viewDidLoad]; CLLocationManager *locationManager =[[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locationManager startUpdatingLocation];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//implementamos los metodos delegados de CLLocationManager.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// this creates a MKReverseGeocoder to find a placemark using the found coordinates
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSString * location = ([placemarks count] > 0) ? [[placemarks objectAtIndex:0] locality] : #"Not Found";
_ciudadLabel.text=location;
}];
}
// this delegate method is called if an error occurs in locating your current location
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"locationManager:%# didFailWithError:%#", manager, error);
}
But when I execute the application, the message that says if I want to allow to get my location disapear suddenly and don't execute:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// this creates a MKReverseGeocoder to find a placemark using the found coordinates
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSString * location = ([placemarks count] > 0) ? [[placemarks objectAtIndex:0] locality] : #"Not Found";
_ciudadLabel.text=location;
}];
}
why the location doesn't start?
Thanks
Related
Is there a way to determine specific places that users are currently in? I would like to show more than the current city or country they are in and instead show lakes, parks, and other things that if searched on a map would correspond to that location (i.e. Sears Tower, Downtown New York, Yellowstone Park). Also, if this is not possible can anyone provide an example showing the updated way of getting which city you are in? Im using Obj-c in Xcode, but I am having trouble doing this. Any help would be appreciated!
Here is the code I'm using so far:
Implementaion
CLLocationManager *locationManager;
ViewDidLoad
locationManager = [[CLLocationManager alloc] init];
Button
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
Void Method
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation: (CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSLog(#"%#", currentLocation);
}
}
Pass the coordinates you receive from LocationManager to CLGeocoder
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:currentLocation completionHandler:
^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0) {
CLPlacemark *placemark = placemarks[0];
NSLog(#"country is: %#", placemark.country );
}
}];
I am using CLLocationManger to get device current location. All is going well on simulation. I check the "Allow Location Simulation" and set Sydney, Australia as default location. I got the lat and long of Sydney on simulator that is fine
My problem is that when i try on device I still get the Sydney location however my device current location is India.
My device get the location what ever I set in Xcode.
Here is my code:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = 1;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
#pragma mark delegate method which tell the current location
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
latitudeCurrentLocation = [NSString stringWithFormat:#"%f",newLocation.coordinate.latitude];
longitudeCurrentLocation= [NSString stringWithFormat:#"%f",newLocation.coordinate.longitude];
[locationManager stopUpdatingLocation];
locationManager=nil;
NSLog(#"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
}
Please suggest what should I should do.
Use this delegate method and check your location address
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
Here is sample code :
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:_locationManager.location
completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"reverseGeocodeLocation:completionHandler: Completion Handler called!");
if (error){
NSLog(#"Geocode failed with error: %#", error);
return;
}
NSLog(#"placemarks=%#",placemarks);
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"placemark.ISOcountryCode =%#",placemark.ISOcountryCode);
NSLog(#"placemark.country =%#",placemark.country);
NSLog(#"placemark.postalCode =%#",placemark.postalCode);
NSLog(#"placemark.administrativeArea =%#",placemark.administrativeArea);
NSLog(#"placemark.locality =%#",placemark.locality);
NSLog(#"placemark.subLocality =%#",placemark.subLocality);
NSLog(#"placemark.subThoroughfare =%#",placemark.subThoroughfare);
NSLog(#"stringlocation:%#",_cityString);
}];
_userLocation = [locations lastObject]; // This will give you co-ordinates
[_locationManager stopUpdatingLocation];
}
When you run this in your device select don't simulate 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];
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];
I have a custom navbar with a locateButton that is visible in every view
When a user taps the locateButton, I would like to update lat and long on every view. I've got it working in one view at a time, with the following code.
ViewController.m
- (UIBarButtonItem *)locateButton {
[locationButton addTarget:self action:#selector(locationPressed:) forControlEvents:UIControlEventTouchUpInside];
}
- (IBAction)locationPressed:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
#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) {
latLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
longLabel.text = [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];
addressLabel.text = [NSString stringWithFormat:#"%#, %#",
placemark.locality,
placemark.administrativeArea];
addressLabel.numberOfLines = 0;
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
I'm trying to add a singleton to accomplish this.
In Location.h
// Location.h
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface Location : NSObject <CLLocationManagerDelegate>
#property (nonatomic, strong) CLLocationManager* locationManager;
+ (Location*)sharedSingleton;
#end
Then in Location.M
// Location.m
#import "Location.h"
#implementation Location
#synthesize locationManager;
- (id)init {
self = [super init];
if(self) {
self.locationManager = [CLLocationManager new];
[self.locationManager setDelegate:self];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
[self.locationManager setHeadingFilter:kCLHeadingFilterNone];
[self.locationManager startUpdatingLocation];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//do any more customization to your location manager
}
return self;
}
+ (Location*)sharedSingleton {
static Location* sharedSingleton;
if(!sharedSingleton) {
#synchronized(sharedSingleton) {
sharedSingleton = [Location new];
}
}
return sharedSingleton;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
[locationManager stopUpdatingLocation];
}
#end
How do I get my - (IBAction)locationPressed:(id)sender in another view let's say HomeViewController.m to call this locationManager method and also update the singleton value?
You might consider a singleton as your location manager and location manager delegate. There are a bunch of stackoverflow questions about creating singletons like this one: Singleton in iOS 5?.
Then when your user clicks that button, your singleton class will be called and updated and other views will look at that same singleton to get their location info.