been having this problem for a few days now and can't seem to find a solution for it. It's probably some very basic stuff but still can't come up with a solution. So I'm trying to have my uilabel update a user speed in a car or on bike. But When the UIlabel update, it doesn't update the correct value. Any help will be appreciated.
Heres my .h file
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface MainViewController : UIViewController <LoginDelegate,WEPopoverParentView,PopoverControllerDelegate,MainMenuDelegate,MKMapViewDelegate,UIActionSheetDelegate,UIAccelerometerDelegate, CLLocationManagerDelegate, NSObject>
{
AppDelegate *appDelegate;
IBOutlet MKMapView *userMap;
CLLocationManager *locationManager;
}
#property (strong, nonatomic) IBOutlet UILabel *speedView;
#property(nonatomic) int speedCount;
#property (nonatomic,retain) CLLocationManager *locationManager;
#property (nonatomic, strong) WEPopoverController *popoverController;
+ (NSString *) speedToMPH: (float) value;
- (IBAction)btnMenuTapped:(id)sender;
#end
and my .h file
#implementation MainViewController
#synthesize speedCount;
#synthesize speedView;
#synthesize popoverController;
#synthesize locationManager;
- (void)locationError:(NSError *)error {
speedView.text = [error description];
}
-(void)viewWillAppear:(BOOL)animated
{
[userMap setRegion:MKCoordinateRegionMakeWithDistance(userMap.userLocation.coordinate, 5, 5) animated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
appDelegate = [[UIApplication sharedApplication] delegate];
locationManager =[[CLLocationManager alloc] init];
// Do any additional setup after loading the view, typically from a nib.
[userMap setCenterCoordinate: userMap.userLocation.coordinate animated: YES];
[self performSelector:#selector(checkForLogin) withObject:nil afterDelay:1];
[self startLocationServices];
// create LM
self.locationManager = [CLLocationManager new];
// set its delegate
[self.locationManager setDelegate:self];
// set configuration
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
// start location services
[self.locationManager startUpdatingLocation];
// create an oldLocation variable if one doesn't exist
}
- (void)startLocationServices
{
// create the Location Manager
if (self.locationManager == nil) {
self.locationManager = [CLLocationManager new];
}
// stop services
[self.locationManager stopUpdatingLocation];
[self.locationManager setDelegate:nil];
self.speedView.text = #"Location Services stopped.";
}
// locationManager didUpdateToLocation FromLocation
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
NSLog(#"%#", newLocation);
self.speedView.text = [NSString stringWithFormat:#"%d %.f ", speedCount, [newLocation speed]];
}
+ (NSString *) speedToMPH: (float) value
{
NSString *speedCount = #"0.0 ";
if (value>0) {
float mile = 1609.344f;
float mph = value / mile * 3600;
speedCount = [NSString stringWithFormat: #"%.f ", mph];
}
return speedCount;
}
CLLocation returns the speed in meters per second. So you will have to convert it to miles per hour by multiplying the value with 2.23694.
self.speedView.text = [NSString stringWithFormat:#"%d %.f ", speedCount, [newLocation speed] * 2.23694];
Related
This is my first post every here. Woohoo.
Here is my story ... I spent about a week trying tutorials about geofencing in IOS. The problem is that i have to do it in Objective-C for now.
I am trying to get a small app to run this geofencing but i keep having problems with the actual trigger events.
I am testing it on my actual phone (iPhone 7Plus) and i can't get to make some events show on the screen whether i'm inside the region or out.
i will paste code from the .h and .m files. these are the only ones that i have implemented so far.
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController <CLLocationManagerDelegate>
#property (weak, nonatomic) IBOutlet UILabel *myLat;
#property (weak, nonatomic) IBOutlet UILabel *myLon;
#property (weak, nonatomic) IBOutlet UILabel *destLat;
#property (weak, nonatomic) IBOutlet UILabel *destLon;
#property (weak, nonatomic) IBOutlet UILabel *diff;
#property (weak, nonatomic) IBOutlet UILabel *answer;
#property BOOL alwaysOn;
#property BOOL isCLickOn;
#property (retain, nonatomic) CLLocationManager *locationManager;
#end
... and this what i have in my .m file:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void) viewDidAppear:(BOOL)animated{
// [self showAlertMessage:#"Test" message:#"Maybe works"];
// [self showAlertMessage:#"Test" message:#"Maybe works"];
[self setupTheAuthorizations];
if(!_isCLickOn){
[self startTheRegionMonitoring];
}
// _answer.text = #"Merge";
}
- (void) setupTheAuthorizations {
_locationManager = [[CLLocationManager alloc] init];
[_locationManager requestAlwaysAuthorization];
_locationManager.delegate = self;
[_locationManager startUpdatingLocation];
//check the type of authorization
CLAuthorizationStatus authStatus = [CLLocationManager authorizationStatus];
switch (authStatus) {
case kCLAuthorizationStatusAuthorizedAlways:
// should do somethinglike getting the things started and stuff like that ...
_alwaysOn = YES;
break;
case kCLAuthorizationStatusNotDetermined:
[_locationManager requestAlwaysAuthorization];
default:
break;
}
}
- (void) startTheRegionMonitoring {
if (_alwaysOn && [CLLocationManager isMonitoringAvailableForClass:[CLRegion class]]){
CLLocationDegrees latitude = 37.972004;
CLLocationDegrees longitude = -121.293740;
CLLocationDistance radius = 200;
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(latitude, longitude);
CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:center radius:radius identifier:#"CH"];
region.notifyOnEntry = YES;
region.notifyOnExit = YES;
_destLat.text = [NSString stringWithFormat:#"%f", latitude];
_destLon.text = [NSString stringWithFormat:#"%f", longitude];
_myLat.text = [NSString stringWithFormat:#"%f", _locationManager.location.coordinate.latitude];
_myLon.text = [NSString stringWithFormat:#"%f", _locationManager.location.coordinate.longitude];
[_locationManager startMonitoringForRegion:region];
}
_isCLickOn = YES;
}
- (void)locationManager:(CLLocationManager *)manager
didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
}
- (void)locationManager:(CLLocationManager *)manager
didEnterRegion:(CLRegion *)region{
NSLog(#"entered region");
if ([region.identifier isEqualToString:#"CH"]){
_answer.text = #"IN";
CLLocation *me = [[CLLocation alloc] initWithLatitude:_locationManager.location.coordinate.latitude
longitude:_locationManager.location.coordinate.longitude];
CLLocation *dest = [[CLLocation alloc] initWithLatitude:37.972004
longitude:-121.293740];
int dist = [me distanceFromLocation:dest];
_diff.text = [NSString stringWithFormat:#"%i", dist];
}
}
- (void)locationManager:(CLLocationManager *)manager
didExitRegion:(CLRegion *)region{
NSLog(#"entered region");
if ([region.identifier isEqualToString:#"CH"]) {
_answer.text = #"OUT";
CLLocation *me = [[CLLocation alloc] initWithLatitude:_locationManager.location.coordinate.latitude
longitude:_locationManager.location.coordinate.longitude];
CLLocation *dest = [[CLLocation alloc] initWithLatitude:37.972004
longitude:-121.293740];
int dist = [me distanceFromLocation:dest];
_diff.text = [NSString stringWithFormat:#"%i", dist];
}
}
- (void)locationManager:(CLLocationManager *)manager
didStartMonitoringForRegion:(CLRegion *)region __OSX_AVAILABLE_STARTING(__MAC_10_8,__IPHONE_5_0) __TVOS_PROHIBITED __WATCHOS_PROHIBITED{
NSLog(#"Monitoring started");
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"error");
}
- (void) showAlertMessage:(NSString *)title message:(NSString *)message {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:cancel];
[self presentViewController:alert animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
What happens is that i don't get any events showing on my phone even when the app is open. so I have a view controller on the storyboard that is supposed to show my location and destination location and to show the distance between the two objects. But it doesn't show it even if i walk 400 meters and then i walk back to the center.
I know that Swift is what I should use, and I will switch to Swift but for right now I am really wanting to understand the process that goes in this geofencing thing.
Any help will be appreciated. I am also pretty new at programming so I still have things that I am trying to learn and understand about Objective-C in particular.
Thank you.
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...
A ViewController starts a LocationTracking. I want to NSLog the location updates (when the simulator is on freeway drive), but didUpdateLocations only logs when I uncomment the NSTimer, I can't figure out why. I feel real dumb asking this, it's probably something simple, I'm new to this and have spent a long time trying to work it out.
ViewController:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:#"locationUpdate"]) {
LocationTracking *locationTracker = [[LocationTracking alloc] init];
[locationTracker startTracking];
NSLog(#"location tracking did");
//NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:locationTracker selector:#selector(logLast) userInfo:nil repeats:YES];
}
}
LocationTracking.h:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface LocationTracking : NSObject <CLLocationManagerDelegate>
#property (nonatomic, strong) NSMutableArray *locations;
-(void) startTracking;
-(void) logLast;
#end
LocationTracking.m:
#import "LocationTracking.h"
#interface LocationTracking()
#property (nonatomic, strong) CLLocationManager *locationManager;
#end
#implementation LocationTracking
-(void)startTracking
{
self.locations = [[NSMutableArray alloc] init];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self.locationManager setDelegate:self];
[self.locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
NSLog(#"did update %#",[locations lastObject]);
}
-(void)logLast
{
}
The following code works fine for me:
#import "ViewController.h"
#import CoreLocation;
#interface ViewController () <CLLocationManagerDelegate>
#property (strong,nonatomic) CLLocationManager *locationManager;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self.locationManager setDelegate:self];
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *loc = [locations lastObject];
NSString *lat = [NSString stringWithFormat:#"%.2f",loc.coordinate.latitude];
NSString *lon = [NSString stringWithFormat:#"%.2f",loc.coordinate.longitude];
NSLog(#"location is: %#, %#",lat,lon);
}
#end
And if you are using the simulator in Xcode, don't forget to set the location for the simulator. It defaults to "None" for new projects.
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);
I was trying to implement a separate class for managing my location. I wanted to get my location whenever I click a button.
gpsFilter.h
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#interface gpsFilter : NSObject <CLLocationManagerDelegate>
#property (nonatomic, retain) CLLocationManager *gpsManager;
#property (nonatomic, retain) NSString * latitude;
#property (nonatomic, retain) NSString * longitude;
#end
gpsFilter.m.
#import "gpsFilter.h"
#implementation gpsFilter
- (id) init{
self = [super init];
if(self != nil){
self.gpsManager = [[CLLocationManager alloc] init];
self.gpsManager.delegate = self;
[self.gpsManager startUpdatingLocation];
BOOL enable = [CLLocationManager locationServicesEnabled];
NSLog(#"%#", enable? #"Enabled" : #"Not Enabled");
}
return self;
}
- (void)gpsManager:(CLLocationManager *) manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if(currentLocation != nil){
self.latitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
self.longitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
- (void)gpsManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
}
#end
I am using a separate class because I wanted to add smoothing filter in the future. I don't get any updates. The NSLog is never triggered. I think some variable is getting autoreleased, but I am not sure, which one.
The viewController code is as follows.
#import "gpstestViewController.h"
#interface gpstestViewController (){
}
#end
#implementation gpstestViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.location = [[gpsFilter alloc] init];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)getloca:(id)sender {
self.latitudeLabel.text = [self.location latitude];
self.longitudeLabel.text = [self.location longitude];
}
- (IBAction)getLocation:(id)sender {
self.latitudeLabel.text = [self.location latitude];
self.longitudeLabel.text = [self.location longitude];
}
#end
I am sorry that I am dumping a lot of code, but I am a newbie to ios programming and I am not able to find what the problem is.
EDIT: The updateLocation delegate method is not being called at all.
The delegate methods must be named locationManager:didUpdateToLocation:fromLocation: and locationManager:didFailWithError:.
You cannot use custom method names like gpsManager:didUpdateToLocation:fromLocation:.
Also note that locationManager:didUpdateToLocation:fromLocation: is deprecated as of iOS 6 and you should use locationManager:didUpdateLocations:.
The signature of your didUpdateToLocation is wrong:
This is my code:
/** Delegate method from the CLLocationManagerDelegate protocol. */
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
// here do
}
Further set the desiredAccuracy to CLLocationAccuracyBest.