I have to find the current location and i am using this code
-(CLLocationCoordinate2D) getLocation{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
return coordinate;
}
- (void)getCurrentLocation{
CLLocationCoordinate2D coordinate = [self getLocation];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"Latitude = %#", latitude);
NSLog(#"Longitude = %#", longitude);
}
but latitude and longitude is coming zero? and i have called these method in viewDidLoad
[self getCurrentLocation];
[self getLocation];
why is it so please help me. thanks
I hope , Following info can help you:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
#end
and add this:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[self.locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
Callback function
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(#"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
NSLog(#"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
You also have to add a string for the
[`NSLocationAlwaysUsageDescription`]
You need to use "CLLocationManagerDelegate".
Just go through this tutorial. How To Get the User Location in iPhone App
Here you will learn about CoreLocation Framework.
This is the delegate method which will return you current lat-long.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
And also make sure your app authorize to use location services.
And Also run your app on device, or if you want to see the result in simulator, follow the steps mentioned in tutorial.
Step 1 : #import <CoreLocation/CoreLocation.h> import framework. Also add framework in your project.
Step 2 : Make sure your view-controller implement CLLocationManagerDelegate
#interface MyLocationViewController : UIViewController <CLLocationManagerDelegate>
Step 3 : Define class instance of CLLocationManager
#implementation MyLocationViewController {
CLLocationManager *locationManager;
}
Step 4 :
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
if([locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
//iOS 8.0 onwards
[locationManager requestAlwaysAuthorization];
}
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
Step 5 : Here is your CLLocationManagerDelegate
method implementation
- (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) {
NSLog(#"Longitude %.8f",currentLocation.coordinate.longitude);
NSLog(#"Latitude %.8f",currentLocation.coordinate.latitude);
}
}
First go to your info.plist and right click on it and select the source code option.
Then add the following lines after the <dict> keyword
<key>NSLocationAlwaysUsageDescription</key>
<string>This App wants to Know your location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This App wants to Know your location</string>
Without this, you can't get CLLocation working in iOS 9.0.
Now follow the instruction.
Import
#import <CoreLocation/CoreLocation.h>
and list the CoreLocation delegate like
#interface ViewController ()<CLLocationManagerDelegate>
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
Then in the viewDidLoad method add the following lines-
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate=self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]){
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
Now implement the delegate methods
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Sorry"
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) {
NSLog(#"%#", [NSString stringWithFormat:#"%.4f", currentLocation.coordinate.longitude]);
NSLog(#"%#", [NSString stringWithFormat:#"%.4f", currentLocation.coordinate.latitude]);
}
}
It takes some time for the CLLocationManager to get the coordinates. Therefore, the CLLocationManager uses a delegate to notify when it received the location updates. Therefore, you cannot get the result immediately. Please have a look at this post to see how it's done.
Well, I wanted you to read the doc, still I am posting the solution.
-(void)viewDidLoad{
[self initLocationManager];
}
-(void)initLocationManager{
self.locationManager=[[CLLocationManager alloc] init];
self.locationManager.delegate=self;
if (([_locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])) {
[_locationManager requestWhenInUseAuthorization];
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self.locationManager startUpdatingLocation];
}
Then handle the location updates in the CLLocationManager delegate method like below
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)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) {
NSLog(#"%f,%f",location.coordinate.latitude,location.coordinate.longitude);
}
}
Update
To make it work, you need to do two things
Enable Background Modes from Capabilities Tab, and choose Location Updates, see image below
Add NSLocationWhenInUseUsageDescription in Info Tab, into the plist, see image
It will start working.
Hope it helps. Cheers.
Use this code it works
firstly add NSLocationAlwaysUsageDescription as string in info.plist
in .h
#import <CoreLocation/CoreLocation.h>
#interface ExamListVC : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager * locationManager;
}
#end
in .m use this code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
locationManager . delegate = self;
[self initLocationManager];
}
-(void)initLocationManager
{
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate=self;
if (([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]))
{
[locationManager requestWhenInUseAuthorization];
}
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0)
{
NSLog(#"Current Coordinates are %f,%f",location.coordinate.latitude,location.coordinate.longitude);
[locationManager stopUpdatingLocation];
}
}
it will give output like
[2390:96060] Current Coordinates are 37.332331,-122.031219
Related
I have to find the current location and i am using this code
-(CLLocationCoordinate2D) getLocation{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
return coordinate;
}
- (void)getCurrentLocation{
CLLocationCoordinate2D coordinate = [self getLocation];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"Latitude = %#", latitude);
NSLog(#"Longitude = %#", longitude);
}
but latitude and longitude is coming zero? and i have called these method in viewDidLoad
[self getCurrentLocation];
[self getLocation];
why is it so please help me. thanks
I hope , Following info can help you:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
#end
and add this:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[self.locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
Callback function
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(#"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
NSLog(#"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
You also have to add a string for the
[`NSLocationAlwaysUsageDescription`]
You need to use "CLLocationManagerDelegate".
Just go through this tutorial. How To Get the User Location in iPhone App
Here you will learn about CoreLocation Framework.
This is the delegate method which will return you current lat-long.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
And also make sure your app authorize to use location services.
And Also run your app on device, or if you want to see the result in simulator, follow the steps mentioned in tutorial.
Step 1 : #import <CoreLocation/CoreLocation.h> import framework. Also add framework in your project.
Step 2 : Make sure your view-controller implement CLLocationManagerDelegate
#interface MyLocationViewController : UIViewController <CLLocationManagerDelegate>
Step 3 : Define class instance of CLLocationManager
#implementation MyLocationViewController {
CLLocationManager *locationManager;
}
Step 4 :
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
if([locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
//iOS 8.0 onwards
[locationManager requestAlwaysAuthorization];
}
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
Step 5 : Here is your CLLocationManagerDelegate
method implementation
- (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) {
NSLog(#"Longitude %.8f",currentLocation.coordinate.longitude);
NSLog(#"Latitude %.8f",currentLocation.coordinate.latitude);
}
}
First go to your info.plist and right click on it and select the source code option.
Then add the following lines after the <dict> keyword
<key>NSLocationAlwaysUsageDescription</key>
<string>This App wants to Know your location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This App wants to Know your location</string>
Without this, you can't get CLLocation working in iOS 9.0.
Now follow the instruction.
Import
#import <CoreLocation/CoreLocation.h>
and list the CoreLocation delegate like
#interface ViewController ()<CLLocationManagerDelegate>
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
Then in the viewDidLoad method add the following lines-
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate=self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]){
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
Now implement the delegate methods
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Sorry"
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) {
NSLog(#"%#", [NSString stringWithFormat:#"%.4f", currentLocation.coordinate.longitude]);
NSLog(#"%#", [NSString stringWithFormat:#"%.4f", currentLocation.coordinate.latitude]);
}
}
It takes some time for the CLLocationManager to get the coordinates. Therefore, the CLLocationManager uses a delegate to notify when it received the location updates. Therefore, you cannot get the result immediately. Please have a look at this post to see how it's done.
Well, I wanted you to read the doc, still I am posting the solution.
-(void)viewDidLoad{
[self initLocationManager];
}
-(void)initLocationManager{
self.locationManager=[[CLLocationManager alloc] init];
self.locationManager.delegate=self;
if (([_locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])) {
[_locationManager requestWhenInUseAuthorization];
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self.locationManager startUpdatingLocation];
}
Then handle the location updates in the CLLocationManager delegate method like below
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)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) {
NSLog(#"%f,%f",location.coordinate.latitude,location.coordinate.longitude);
}
}
Update
To make it work, you need to do two things
Enable Background Modes from Capabilities Tab, and choose Location Updates, see image below
Add NSLocationWhenInUseUsageDescription in Info Tab, into the plist, see image
It will start working.
Hope it helps. Cheers.
Use this code it works
firstly add NSLocationAlwaysUsageDescription as string in info.plist
in .h
#import <CoreLocation/CoreLocation.h>
#interface ExamListVC : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager * locationManager;
}
#end
in .m use this code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
locationManager . delegate = self;
[self initLocationManager];
}
-(void)initLocationManager
{
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate=self;
if (([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]))
{
[locationManager requestWhenInUseAuthorization];
}
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0)
{
NSLog(#"Current Coordinates are %f,%f",location.coordinate.latitude,location.coordinate.longitude);
[locationManager stopUpdatingLocation];
}
}
it will give output like
[2390:96060] Current Coordinates are 37.332331,-122.031219
I am using below code for getting longitude and latitude , but it gives me diifferent values even if I am not moving from my place
locationmanager=[[CLLocationManager alloc]init];
geocoder=[[CLGeocoder alloc]init];
locationmanager.delegate=self;
locationmanager.desiredAccuracy=kCLLocationAccuracyBest;
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
[locationmanager requestWhenInUseAuthorization];
}
[locationmanager startUpdatingLocation];
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"error" message:#"Failed to get Location." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentlocation=newLocation;
if (currentlocation!=nil)
{
longitude=currentlocation.coordinate.longitude;
latitude=currentlocation.coordinate.latitude;
}
[geocoder reverseGeocodeLocation:currentlocation completionHandler:^(NSArray *placemarks, NSError *error) {
} ];
}
please guide me, I want same location, if I am not moving from my place.
Cellular network location gives an approximate area were the phone existing. It is based on the service providers tower.So current location will automatically changes a bit depending on network/gps location tracking/accuracy.
I recommend you to get location using distance filter, so until you are in that region your current address will remain same as location only updates for every X meters.
locationManager.distanceFilter = 100;//Your own distance
i.e.,
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
_locationManager.delegate = self;
// This is the most important property to set for the manager. It ultimately determines how the manager will
// attempt to acquire location and thus, the amount of power that will be consumed.
_locationManager.distanceFilter = 100;
// Once configured, the location manager must be "started".
[_locationManager startUpdatingLocation];
Hope this helps.
In ViewController.h file:
#interface ViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *location;
}
In ViewController.m file:
- (void)viewDidLoad
{
location = [[CLLocationManager alloc] init];
location.delegate = self;
location.distanceFilter = 100;
[location requestWhenInUseAuthorization];
[location requestAlwaysAuthorization];
[location startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *locati = [locations lastObject];
float lat=locati.coordinate.latitude;
float lon=locati.coordinate.longitude;
NSLog(#"%f %f",lat,lon);
[location stopUpdatingLocation];
}
In your info.plist add :
I am using Core Location framework to getting location in iOS. I use, CLLocationManager *locationManager; and call [locationManager startUpdatingLocation];
Problem is I only need instantaneous location but startUpdatingLocation keep on giving me location. To stop this I can use [self.locationManager stopUpdatingLocation], but this look like a way out or hack.
Is there any better way to just get current location in iOS?
in your .h file
#import <CoreLocation/CoreLocation.h>
#interface LocationSearchViewController : UIViewController<UITextFieldDelegate,CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
}
in your .m file
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
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);
[locationManager stopUpdatingLocation]; // when u got the lat and long it stop uoatde the location
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSString *getcurrlong = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
NSSting *getcurrlat = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
You can't think of location in those precise terms. You'll get back increasingly accurate locations from the location manager and it's up to you to decide when it's accurate enough. You have to weigh this against power usage and time. The location updates will never be completely accurate. The will never be returned immediately. The device has to power up hardware, then listen for GPS/WiFi/Cell signals and use all those to calculate location.
There's no way to ask for "my precise current location" and have it given to you immediately. Location is not a property like [NSDate date]. You can only ask for best-estimate location updates and they will only come to you in imprecise measurements, and never instantaneously (excepting cached location).
Check it
-(void)getCurrentLocation
{
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
startLocation = nil;
}
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if (startLocation == nil)
{
startLocation = newLocation;
[locationManager setDelegate:nil];
locationManager = nil;
}
}
I have the following code:
- (void) viewWillAppear {
[self startSignificantChangeUpdates];
}
- (void)startSignificantChangeUpdates
{
if ([CLLocationManager locationServicesEnabled])
{
NSLog(#"start significant changes");
if (nil == locationManager)
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startMonitoringSignificantLocationChanges];
}
}
problem is that the location manage is not calling its delegate function
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
What can I do?
In your .h file:
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController <CLLocationManagerDelegate>
In your .m file:
#implementation ViewController {
// This is a private variable, used within this file only
CLLocationManager *locationManager;
}
-(void)viewDidLoad {
locationManager = [[CLLocationManager alloc] init];
}
-(void)viewWillAppear {
// If the delegate is still not being set, try putting this code into viewDidAppear
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
-(void)locationManger:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(#"didFailWithError: %#", error);
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
NSLog(#"didUpdateToLocation: %#", [locations lastObject]);
CLLocation *currentLocation = [locations lastObject];
[locationManager stopUpdatingLocation];
}
For more information about getting the user's location, look at this guide, which I used to implement location into an app of mine: http://www.appcoda.com/how-to-get-current-location-iphone-user/
How are you testing this? If you are running this in the simulator, you can go to Debug->Location->Freeway Drive. You can put a break point in locationManager:didUpdateToLocation method or even put a log statement to log the current location coordinates. You should see it work.
Please replace this line
[locationManager startMonitoringSignificantLocationChanges];
with this code
[locationController.locationManager startUpdatingLocation];
and then check
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
}
I want to get the coordinates of the user, once user starts the app it should initialise GPS coordinates. I have followed this tutorial:
http://www.iosdevnotes.com/2011/10/ios-corelocation-tutorial/
I have created a class named CurrentLocationWithGPS
This is the header:
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#interface CurrentLocationWithGPS : NSObject<CLLocationManagerDelegate>
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;
- (void) getLocations;
- (Float32) latitude;
#property (strong, nonatomic) CLLocationManager *locationManager;
#property (strong, nonatomic) CLLocation *currentLocation;
#end
This is the implementation:
#import "CurrentLocationWithGPS.h"
#implementation CurrentLocationWithGPS
#synthesize locationManager, currentLocation;
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.currentLocation = newLocation;
if(newLocation.horizontalAccuracy <= 100.0f) { [locationManager stopUpdatingLocation]; }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if(error.code == kCLErrorDenied) {
[locationManager stopUpdatingLocation];
} else if(error.code == kCLErrorLocationUnknown) {
// retry
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error retrieving location"
message:[error description]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
- (void) getLocations {
NSLog(#"GPS Location is initialising...");
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
NSLog(#"GPS Location is initialised...");
}
- (Float32) latitude {
return currentLocation.coordinate.latitude;
}
- (Float32) longitude {
return currentLocation.coordinate.longitude;
}
#end
I call the getLocations function in a separate thread so that it wouldn't block anything else. Here is how I call it from another class:
- (void)viewDidLoad
{
[super viewDidLoad];
NSThread *myThread =[[NSThread alloc]initWithTarget:self selector:#selector(locationSet) object:nil];
[myThread start];
}
- (void) locationSet {
CurrentLocationWithGPS *locationFind = [[CurrentLocationWithGPS alloc] init];
locationFind.getLocations;
NSLog(#"latitude is %f", locationFind.latitude);
}
Now the problem is both latitude and longitdute functions are returning 0.000, what am I missing here? I am developing for iOS6.1.
First conforms CLLocationManagerDelegate in .h file like this
#interface CurrentLocationWithGPS : NSObject<CLLocationManagerDelegate>
You need to set CLLocation's Delegate in this method.
- (void) getLocations
{
NSLog(#"GPS Location is initialising...");
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
NSLog(#"GPS Location is initialised...");
}
Do you getting the Current Location on the output . Or R you just trying to retrieve the Co-ordinates ?..
It's still confusing , anyhow
Put this part of code on Your getLocations method
I Hope that You are not at all checking with Location Services . You
Should enable the LocationServices for your app else You always get
null values Check with the Condition:
if ([CLLocationManager locationServicesEnabled])
{
}
For Example :
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager locationServicesEnabled])
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];;
NSString *str=[[NSString alloc] initWithFormat:#" latitude:%f longitude:%f",coordinate.latitude,coordinate.longitude];
And Let me know , .????