I try to update device's location course real time.
I am doing some experiment, and i make the VC as CLLocationManager's delegate. But when i run the app, the course information is not updating at all. i did set up a breakpoint in the delegate setting line, but the location manager is nil from the debugging area.
What is the problem?
#import "CourseInfomationViewController.h"
#interface CourseInfomationViewController ()
- (IBAction)startMoveLocation:(id)sender;
#end
#implementation CourseInfomationViewController
{
CLLocationManager *_locationManager;
CLLocation *_deviceLocation;
double _deviceDirection;
double _altitude;
double _speed;
}
-(id)init {
if (self = [super init]) {
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
//
_deviceLocation = [[CLLocation alloc] init];
}
return self;
}
- (IBAction)startMoveLocation:(id)sender {
[_locationManager startUpdatingLocation];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - location Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
_deviceLocation = [locations lastObject];
_altitude = _deviceLocation.altitude;
_deviceDirection = _deviceLocation.course;
_speed = _deviceLocation.speed;
NSLog(#"altitude is %f", _altitude);
NSLog(#"altitude is %f", _deviceDirection);
NSLog(#"altitude is %f", _speed);
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(#"%#", error);
}
Related
I've been unable to figure out why location manager isn't providing updates to me. I've added the key, tested on simulator and on a device.
Edit: STDOUT also contains "Delegate: "
STDOUT
2014-11-28 22:18:30.066 Speedo[14091:150298] Status: 4
2014-11-28 22:18:30.069 Speedo[14091:150298] Is when in use? 1
2014-11-28 22:18:30.158 Speedo[14091:150298] New status: 4
2014-11-28 22:18:30.159 Speedo[14091:150298] Is when in use? 1
FirstViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface FirstViewController : UIViewController <CLLocationManagerDelegate>
#property (weak, nonatomic) IBOutlet UILabel* speedLabel;
#end
FirstViewController.cpp
#import "FirstViewController.h"
#import <CoreLocation/CoreLocation.h>
#interface FirstViewController ()
#end
#implementation FirstViewController {
CLLocationManager *locationManager;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
self.speedLabel.text = #"";
if([locationManager respondsToSelector: #selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
// locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// locationManager.distanceFilter = 0.01;
[locationManager startUpdatingLocation];
NSLog(#"Delegate: %#", locationManager.delegate);
NSLog(#"Status: %d", [CLLocationManager authorizationStatus]);
NSLog(#"Is when in use? %d", [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#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 didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
NSLog(#"New status: %d", status);
NSLog(#"Is when in use? %d", [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse);
[manager startUpdatingLocation];
}
-(void)locationManage: (CLLocationManager *)manager didUpdateLocations:(NSArray*)locations {
CLLocation* last = [locations lastObject];
NSLog(#"Speed: %f m/s", last.speed); // meter per second
// TODO: support mutli-units
// m/s -> mph
// 1 -> 2.236
self.speedLabel.text = [NSString stringWithFormat:#"%d", (int)(last.speed * 2.23694)];
}
#end
Perhaps it's just the result of a typo.
-(void)locationManage: (CLLocationManager *)manager didUpdateLocations:(NSArray*)locations {
should be
-(void)locationManager: (CLLocationManager *)manager didUpdateLocations:(NSArray*)locations {
You forgot the "r" at the end of "locationManager".
Calling class...
#implementation MenuViewController
- (void)viewDidLoad {
[super viewDidLoad];
FuelSiteLocator *siteLocator = [[FuelSiteLocator alloc]init];
[siteLocator getStations:#"Unleaded Regular"];
...
}
And this is the class that isn't working...
#implementation FuelSiteLocator {
CLLocationManager *locationManager;
}
-(id) initWithSearchType {
locationManager = [CLLocationManager new];
[locationManager setDelegate:self];
return self;
}
-(void) getStations:(NSString *)search {
[self setSearchType:search];
[locationManager startMonitoringSignificantLocationChanges];
}
-(void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(#"%#", error.description);
}
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
[self getGasStations:[locations lastObject]];
}
-(void) getGasStations:(CLLocation *) currentLocation {
NSLog(#"Hello Gas Stations..");
}
The delegate methods are not being called and I have no idea why... In FuelSiteLocator.h I'm using the CLLocationManagerDelegate protocol
****Problem Solved*******
ARC is releasing the siteLoactor object after getStations is called. The delegate methods never had a chance
As mentioned earlier in the comments, your init method is not correct.
try:
-(id) initWithSearchType:(NSString *)search {
self = [super init];
if (self) {
self.searchType = search;
self.locationManager = [CLLocationManager new];
self.locationManager.delegate = self;
}
return self;
}
(This assumes the class inherits from NSObject, as I haven't seen the class definition).
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.
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.
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.