Trying to get current location, but LocationManager delegate never get called - ios

here is my code, i am trying to get my current longtitude and latitude,
so my location will be display on map view.
however, the location manager delegate never get called, so i always getting longitude = 0.0000 and latitude = 0.0000.....
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface MapViewController : UIViewController <CLLocationManagerDelegate>
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#property(retain,nonatomic)CLLocationManager *locationManager;
#property(assign,nonatomic)float longitude;
#property(assign,nonatomic)float latitude;
#end
and this is the implementation file:
#import "MapViewController.h"
#define METERS_PER_MILE 1609.344
#interface MapViewController ()
#end
#implementation MapViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
[self getCurrentLocation];
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = self.latitude;
zoomLocation.longitude = self.longitude;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
[self.mapView setRegion:viewRegion animated:YES];
NSLog(#"longitu
de %f", self.longitude);
NSLog(#"latitude %f", self.latitude);
}
-(void)getCurrentLocation
{
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidUnload {
[self setMapView:nil];
[super viewDidUnload];
}
-(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 didUpdateLocations:(NSArray *)locations
{
NSLog(#"didUpdateToLocation: %#", [locations lastObject]);
CLLocation *currentLocation = [locations lastObject];
if (currentLocation != nil) {
self.longitude = currentLocation.coordinate.longitude;
self.latitude = currentLocation.coordinate.latitude;
NSLog(#"cal longitude %f", self.longitude);
NSLog(#"cal latitude %f", self.latitude);
}
}
#end
can anyone give me some advise please. cheers

May be you are running the code on simulator and SDK is below 6.0. In this case you get only 0.0000 as latitude and longitude. And make sure that application is granted access to device location.
If you just want to get current location then do the following :
-(void)getCurrentLocation
{
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
CLLocation currentLocation = self.locationManager.location;
[self.locationManager stopUpdatingLocation];
}
BTW, never use self when initialize any object. Because doing this creates 2 object.
first object is created by right side of this line self.locationManager = [[CLLocationManager alloc] init];. Second object is created when setter method is called by left side of the same line, to assign an object to locationManager variable.

Related

Core Location delegate methods not getting called in iOS 8.3 Xcode 6.3.1

I am trying to get the user's current location using the Core Location Framework in Xcode 6.3.1, I did following things:
Added Core Location Framework under Target-> General-> Linked Frameworks & Libraries
My ViewController.h file is as shown below,
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController<CLLocationManagerDelegate>
#property (weak, nonatomic) IBOutlet UILabel *lblLatitude;
#property (weak, nonatomic) IBOutlet UILabel *lblLongitude;
#property (weak, nonatomic) IBOutlet UILabel *lblAddress;
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
My ViewController.m file is as shown below,
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
if(IS_OS_8_OR_LATER){
NSUInteger code = [CLLocationManager authorizationStatus];
if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])) {
if([[NSBundle mainBundle] objectForInfoDictionaryKey:#"NSLocationAlwaysUsageDescription"]){
[self.locationManager requestAlwaysAuthorization];
} else if([[NSBundle mainBundle] objectForInfoDictionaryKey:#"NSLocationWhenInUseUsageDescription"]) {
[self.locationManager requestWhenInUseAuthorization];
} else {
NSLog(#"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
}
}
}
[self.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) {
lblLatitude.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
lblLongitude.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
#end
I had also added the following keys in my info.plist file
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
Checked everything given here, here, here, here, and a lot more list
So, is anyone having a solution for this issue, kindly help. Have lost my mind searching for this for the whole day.
Yeah! Got the solution, Here is my whole code & things added to make it working. Special thanks to #MBarton for his great help. Also Thanks to # Vinh Nguyen for investing his precious time in solving my issue.
Added Core Location Framework under Target-> General-> Linked Frameworks & Libraries
Added in .plist file
NSLocationAlwaysUsageDescription
See Screenshot:
In my ViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>
// #define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
#interface ViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>
{
__weak IBOutlet UINavigationItem *navigationItem;
}
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#property(nonatomic, retain) CLLocationManager *locationManager;
#end
Then in ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize mapView;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self setUpMap];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)setUpMap
{
mapView.delegate = self;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
// if(IS_OS_8_OR_LATER) {
if ([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
mapView.showsUserLocation = YES;
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:YES];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
NSLog(#"%#", [self deviceLocation]);
//View Area
MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = self.locationManager.location.coordinate.latitude;
region.center.longitude = self.locationManager.location.coordinate.longitude;
region.span.longitudeDelta = 0.005f;
region.span.longitudeDelta = 0.005f;
[mapView setRegion:region animated:YES];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}
- (NSString *)deviceLocation {
return [NSString stringWithFormat:#"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
}
Ufff...! Got the solution after fighting with many codes since last 5 days...

Local push notification by GPS position

I have a simple question about iOS, GPS Location and push notification.
Is possible in iOS to send a local push notification when the device is near of a specific GPS position?
Following code for ViewController.h file
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController <CLLocationManagerDelegate>{
CLLocationManager *locationManager;
NSString* lastNotification;
}
#end
Following code for ViewController.m file
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
lastNotification = #"";
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark -User Actions
- (IBAction)startLocaingMe:(id)sender{
[self startLocationReporting];
}
#pragma mark - Location Metods
- (void)startLocationReporting {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;//or whatever class you have for managing location
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locationManager startUpdatingLocation];
}
// Delegate method from the CLLocationManagerDelegate protocol.
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
// If it's a relatively recent event, turn off updates to save power
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0) {
[self showNotificationIfDistanceIs100: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);
}
- (CLLocationDistance)distanceBetweenTwoPoints:(CLLocation*) location1 andSecond:(CLLocation*) location2{
CLLocationDistance distance = [location1 distanceFromLocation:location2];
return distance;
}
-(CLLocation*)House{
CLLocation *loc = [[CLLocation alloc] initWithLatitude:23.030064 longitude:72.546193];
return loc;
}
-(CLLocation*)passportOffice{
CLLocation *loc = [[CLLocation alloc] initWithLatitude:23.032034 longitude:72.549999];
return loc;
}
-(CLLocation*)ldCollageBusStand{
CLLocation *loc = [[CLLocation alloc] initWithLatitude:23.032515 longitude:72.549307];
return loc;
}
-(void)showNotificationIfDistanceIs100:(CLLocation*) location{
if ([self distanceBetweenTwoPoints:location andSecond:[self House]] <= 100) {
[self setLocalNotificaion:#"Your are 100 meter form House"];
}else if ([self distanceBetweenTwoPoints:location andSecond:[self passportOffice]] <= 100){
[self setLocalNotificaion:#"Your are 100 meter form Passport Office"];
}else if ([self distanceBetweenTwoPoints:location andSecond:[self ldCollageBusStand]] <= 100){
[self setLocalNotificaion:#"Your are 100 meter form Ld Collage Bus Stand"];
}
}
-(void)setLocalNotificaion:(NSString*)msg{
if ([lastNotification isEqualToString:msg] != YES) {
lastNotification = msg;
UILocalNotification *futureAlert;
futureAlert = [[UILocalNotification alloc] init];
[futureAlert setAlertBody:msg];
futureAlert.fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
futureAlert.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:futureAlert];
}
}
#end
You can change location Long/Lati and getting the Localnotification
May this thinks lot helpful
-------EDITED---------
You can implement LocationManager instance and get notified about location updates in the following method:
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// CLLocation object will be the content of the array locations
}
You can post UILocalNotification based on your requirements.

Cannot get latitude and longtidute with CoreLocation in Objective-C

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 , .????

iOS CoreLocation not getting GPS coordinates

So I am new to iOS development, and I am just trying to get a label updated with my current GPS Coordinates. I am not having an issue compiling, but my coordinates are coming up as 0.00000, 0.00000.
Here is the code for my .h file:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController{
IBOutlet CLLocationManager *locationManager;
IBOutlet UILabel *location;
}
//#property (nonatomic, retain) IBOutlet CLLocationManager *locationManager;
//#property (weak, nonatomic) IBOutlet UILabel *location;
#end
Here is the code for my .m file:
#implementation ViewController
- (void) updateLabel
{
NSObject *latitude = [NSString stringWithFormat:#"%f", locationManager.location.coordinate.latitude];
NSObject *longitude = [NSString stringWithFormat:#"%f", locationManager.location.coordinate.longitude];
location.text = [NSString stringWithFormat: #"%#,%#", latitude, longitude];
}
- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[self updateLabel];
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Fixed it:
I wasn't implementing any delegate methods, and I was not implementing [locationManager startUpdatingLocation]. Now I know better.
.h File:
#interface MapViewController : UIViewController <CLLocationManagerDelegate>
#property (nonatomic, retain) IBOutlet CLLocationManager *locationManager;
#property (strong, nonatomic) IBOutlet UILabel *location;
#end
.m File:
- (void) updateCurrentLabel
{
NSObject *latitude = [NSString stringWithFormat:#"%f", locationManager.location.coordinate.latitude];
NSObject *longitude = [NSString stringWithFormat:#"%f", locationManager.location.coordinate.longitude];
self.location.text = [NSString stringWithFormat: #"Current Location: %#,%#", latitude, longitude];
}
- (void)viewDidLoad
{
[self getCurrentLocation];
[super viewDidLoad];
}
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
[self updateCurrentLabel];
}
-(void) getCurrentLocation
{
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
Thanks for pointing out how nooby I was. Figured it out. Thanks guys!
once try like this,in ViewDidLoad:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = (id)self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[locationManager startUpdatingLocation];
[self updateLabel];
Use this Delegate Method otherwise you will get 0 values:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
//No need to do any code...
// NSLog(#"Got location %f,%f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
In Updating Label Method :
- (void) updateLabel
{
//Getting Current Latitude and longitude..
CLLocation *location = [locationManager location];
float longitude=location.coordinate.longitude;
float latitude=location.coordinate.latitude;
NSLog(#"latitude,longitudes are >> %f,%f",latitude,longitude);
locationlabel.text = [NSString stringWithFormat:#"%f,%f",longitude,latitude];
}
Instead of using locationManager.location.coordinate.latitude, keep an instance variable of type CLLocationCoordinate2D. You can call it something like currentLocation. Then when you get a value in the delegate method locationManager:didUpdateLocations:, set the value of currentLocation.
You'll have to call [locationManager startUpdatingLocation] and set its delegate too (as well as implementing that delegate method).
The way you're using the location manager at the moment is wrong and I think you'd be better off following a tutorial to get the basics down.
I find this is fascinating to use location as singleton, and save the values into default user . I am young programmer and am trying to code all in oop. I use this as follow ( this code still need to be refactored and alertUserWithTitle: is a class method of NYMessageToUser to alert user):
//##Header file:
#interface NYLocationManager : NSObject<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
float lonngitude;
float latitude;
float altitude;
}
#property(nonatomic,retain)CLLocationManager *locationManager;
#property(nonatomic,readwrite)float longitude;
#property(nonatomic,readwrite)float latitude;
#property(nonatomic,readwrite)float altitude;
+(NYLocationManager *) getInstance;
-(void)startUpdatingLocation;
-(void)stopUpdatingLocation;
-(double)getDistanceFromUserLocationToCordinatesLatitude:(float)lat Longitude:(float)lon;
#end
//### implementation file:
#implementation NYLocationManager
#synthesize locationManager;
#synthesize latitude;
#synthesize longitude;
#synthesize altitude;
+ (id)getInstance
{
static NYLocationManager *Instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Instance = [[self alloc] init];
});
[Instance startUpdatingLocation];
return Instance;
}
- (id)init
{
if (self = [super init])
{
latitude =0.0;
longitude =0.0;
altitude =0.0;
if([[NSUserDefaults standardUserDefaults] objectForKey:#"locationLongitude"] != nil)
{
NSUserDefaults *savedLocation=[NSUserDefaults standardUserDefaults];
latitude =[[savedLocation objectForKey:#"locationLatitude"] floatValue];
longitude =[[savedLocation objectForKey:#"locationLongitude"] floatValue];
altitude =[[savedLocation objectForKey:#"locationAltitude"] floatValue];
}
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
locationManager.delegate = self;
if ([CLLocationManager locationServicesEnabled])
{
[locationManager startUpdatingLocation];
} else
{
[NYMessageToUser alertUserWithTitle:#"Location Services is Disabled!!!" withMessage:#"This app is designed to share images with location, Please enable location for this app and relucnh the app"];
}
}
return self;
}
- (void)dealloc
{
// Should never be called, but just here for clarity really.
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *loc =[locations lastObject];
self.longitude =loc.coordinate.longitude;
self.latitude =loc.coordinate.latitude;
self.altitude =loc.altitude;
NSUserDefaults *savedLocation=[NSUserDefaults standardUserDefaults];
[savedLocation setObject: [NSString stringWithFormat:#"%f", self.longitude] forKey:#"locationLongitude"];
[savedLocation setObject: [NSString stringWithFormat:#"%f", self.latitude] forKey:#"locationLatitude"];
[savedLocation setObject: [NSString stringWithFormat:#"%f", self.altitude ] forKey:#"locationAltitude"];
[savedLocation synchronize];
[locationManager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
[locationManager stopUpdatingLocation];
[NYMessageToUser alertUserWithTitle:#"Location Error!!!" withMessage:#"This app is designed to use with valid location, Please enable location for this app and relucnh the app"];
}
-(void)startUpdatingLocation
{
if ([CLLocationManager locationServicesEnabled])
{
[locationManager startUpdatingLocation];
} else
{
[NYMessageToUser alertUserWithTitle:#"Location Services is Disabled!!!" withMessage:#"This app is designed to share images with location, Please enable location for this app and relucnh the app"];
}
}
-(void)stopUpdatingLocation
{
[locationManager stopUpdatingLocation];
}
-(double)getDistanceFromUserLocationToCordinatesLatitude:(float)lat Longitude:(float)lon
{
CLLocation *locA = [[CLLocation alloc] initWithLatitude:self.latitude longitude:self.longitude];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
CLLocationDistance distance = [locA distanceFromLocation:locB];
return distance;
}
#end
//### How to use
NYLocationManager *loc =[NYLocationManager getInstance];
NSLog(#"longitude: %f, latitude: %f, altitude: %f",loc.longitude,loc.latitude,loc.altitude);

corelocation keeps looping

I essentially started off with this CoreLocation iOS tutorial to get my head around how to implement CoreLocation into my app. (http://www.techotopia.com/index.php/An_Example_iOS_5_iPhone_Location_Application)
But what I have encountered when trying to incorporate this tutorial into my app is that it now just keeps on looping over and over, which is just baffling me. Can anyone please help?
GPSViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface GPSViewController : UIViewController
#property (strong, nonatomic) CLLocationManager *locationManager;
#property (strong, nonatomic) CLLocation *startLocation;
#end
GPSViewController.m
#import "GPSViewController.h"
#import "DataClass.h"
#interface GPSViewController ()
#end
#implementation GPSViewController
#synthesize locationManager, startLocation;
DataClass *obj;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//initialization og global varable.
DataClass *obj=[DataClass getInstance];
//GPS Initialise
self.locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
startLocation = nil;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark -
#pragma mark CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSString *currentLatitude = [[NSString alloc]
initWithFormat:#"%g",
newLocation.coordinate.latitude];
//latitude.text = currentLatitude;
obj.Latatude = currentLatitude;
NSString *currentLongitude = [[NSString alloc]
initWithFormat:#"%g",
newLocation.coordinate.longitude];
//longitude.text = currentLongitude;
obj.Longitude = currentLongitude;
NSLog(#"latitude %+.6f, longitude %+.6f\n",
newLocation.coordinate.latitude,
newLocation.coordinate.longitude);
if(obj.Latatude != NULL && obj.Longitude != NULL){
[self performSegueWithIdentifier:#"GPSSuccess" sender:self];
}
}
-(void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.startLocation = nil;
self.locationManager = nil;
}
#end
You should call [locationManager stopUpdatingLocation]; in order to stop it from getting the user's location over and over.

Resources