Delegate method not being sent - ios

I don´t understand why the delegate is not sent the message mapView:didUpdateUserLocation:
In viewDidLoad i ask the mapView to startUpdating with setShowUserLocation:YES. But it´s like it never accomplish this.
Any suggestions?
#import "TrackViewController.h"
#import "MainWindowViewController.h"
#class MainWindowViewController;
#implementation TrackViewController
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
NSLog(#"Init trackcontriller");
self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self){
locationManager = [[CLLocationManager alloc]init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
}
return self;
}
-(IBAction) back:(id)sender{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void) findLocation;
{
NSLog(#"findlocation");
[locationManager startUpdatingLocation];
}
-(void) foundLocation:(CLLocation *)loc
{
NSLog(#"Foundlocation");
CLLocationCoordinate2D coord = [loc coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 100, 100);
[worldView setRegion:region animated:YES];
[locationManager stopUpdatingLocation];
}
-(void)viewDidLoad
{
NSLog(#"viewDidLoad");
[worldView setShowsUserLocation:YES];
[worldView setMapType:MKMapTypeHybrid];
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
NSLog(#"mapview didupdateUserlocation");
CLLocationCoordinate2D loc = [userLocation coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 200, 200);
[worldView setRegion:region animated:YES];
}
-(void)dealloc
{
[locationManager setDelegate:nil];
}
- (void) locationManager:(CLLocationManager *) manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
// Deprecated i know
{
NSLog(#"Locationanager didupdate tolocation from location");
NSTimeInterval t = [[newLocation timestamp] timeIntervalSinceNow];
if(t<-180){
return;
}
[self foundLocation:newLocation];
}
-(void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(#"Could not find location: %#", error);
}
#end

I think that you mix up the location services of CLLocationManager and of MapView. mapView:didUpdateUserLocation: is a delegate method of MKMapView. If you just need this method to update the user's location, you don't have to instantiate a CLLocationManager. Instead you simply say, as you did, [worldView setShowsUserLocation:YES];
But of course, your object that implements mapView:didUpdateUserLocation: has to be the delegate of you MKMapView object, here of worldView, not of a CLLocationManager object!
So my suggestion is to set your TrackViewController object as the delegate of your MKMapView object, i.e. of worldView, and delete the code related to the CLLocationManager.

Related

CLLocation Manager Delegates Not Called?

I have made one demo for getting Current Location.
I have used .GPX file for my current Location.
I have used Delegates method of CLLocation Method.
I have Also use Key "Privacy - Location When In Use Usage Description" in my plist file.
I know this question already asked so many time but could not able to get result.
code is
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface ViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
#property (nonatomic,assign)CLLocationCoordinate2D cordinateLocation;
#property (nonatomic,strong)MKPointAnnotation *point;
#property (nonatomic,weak)IBOutlet MKMapView *mapView;
#end
#implementation ViewController
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.mapView.delegate = self;
[self updateCurrentLocation];
}
- (void)updateCurrentLocation {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}
//-(void)getCurrentLocation
//{
// [locationManager requestWhenInUseAuthorization];
// locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// [locationManager startUpdatingHeading];
// [locationManager startUpdatingLocation];
//
//}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertController *errorAlert =[UIAlertController alertControllerWithTitle:#"Error" message:#"error reported" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *alertStyle = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil];
[errorAlert addAction:alertStyle];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
CLLocation *updatedLocation = [locations lastObject];
if(updatedLocation != nil)
{
self.cordinateLocation=CLLocationCoordinate2DMake(updatedLocation.coordinate.latitude, updatedLocation.coordinate.longitude);
[manager stopUpdatingLocation];
[self setCurrentLocationFocus];
}
else{
NSLog(#"Can't access desire location");
}
}
-(void)setCurrentLocationFocus{
MKCoordinateRegion region;
region.center = self.cordinateLocation;
//Adjust span as you like
MKCoordinateSpan span;
span.latitudeDelta = 1;
span.longitudeDelta = 1;
region.span = span;
[self.mapView setRegion:region animated:YES];
///Drop the pin on Current Locatio ////
self.point = [[MKPointAnnotation alloc] init];
self.point.coordinate = self.cordinateLocation;
self.point.title = #"FlockStation";
self.point.subtitle = #"It Department";
[self.mapView addAnnotation:self.point];
//set a new camera angle
MKMapCamera *newCamera=[[MKMapCamera alloc] init];
[newCamera setCenterCoordinate:self.cordinateLocation];
[newCamera setPitch:60.0]; ///For zooming purpose///
[newCamera setHeading:90]; ///For Compass Purpose ///
[newCamera setAltitude:100.0]; ///On which height you want to see your map ///
[self.mapView setCamera:newCamera animated:YES];
}
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:#"NewViewController"];
[self presentViewController:viewController animated:YES completion:nil];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
// self.updatedHeading.text = [NSString stringWithFormat:#"%f",newHeading.magneticHeading];
}
Help Me guys not able to get location.Because delegates method is not calling.
Every Time it called this method.
- (void)locationManager:(CLLocationManager *)manager didFailWithError:`(NSError *)error
You need to check permission of location. then after you can call the delegate methods.
- (void)viewDidLoad {
[super viewDidLoad];
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
[locationManager requestWhenInUseAuthorization];
}
if ([CLLocationManager locationServicesEnabled]){
NSLog(#"Location Services Enabled");
if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){
alert = [[UIAlertView alloc] initWithTitle:#"Permission Denied"
message:#"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentLocation = newLocation;
txtlocations.text = [NSString stringWithFormat:#"%f & %f",currentLocation.coordinate.latitude, currentLocation.coordinate.longitude];
}
Tried with your code with little changes and its working fine.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self updateCurrentLocation];
}
- (void)updateCurrentLocation {
if([CLLocationManager locationServicesEnabled] &&
[CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
[locationManager requestWhenInUseAuthorization];
[locationManager startMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];
// show the map
} else {
// show error
}
}

Zoom in to current location on map

I want to show the current location of the user on the map and zoom on to it.
I tried as follows:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
NSLog(#"Init MapViewController");
[self initMap];
}
return self;
}
-(void) initMap
{
_mapView = [[MKMapView alloc] initWithFrame:self.view.frame];
_mapView.delegate = self;
_mapView.showsUserLocation = YES;
[self.view addSubview:_mapView];
CLLocationCoordinate2D currentLocation;
currentLocation.latitude = _mapView.userLocation.coordinate.latitude;
currentLocation.longitude= _mapView.userLocation.coordinate.longitude;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(currentLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
[_mapView setRegion:viewRegion animated:YES];
}
Then in the simulator it shows a location in the sea. I set the location to London in the simulator.
Just do This:
#property (strong, nonatomic) CLLocationManager *locationManager;
In viewdidload:
self.locationManager = [[CLLocationManager alloc] init] ;
self.locationManager.delegate = (id)self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation ;
[self.locationManager setDistanceFilter:10.0f] ;
[self.locationManager startUpdatingLocation];
And in your location manager
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
[self.locationManager stopUpdatingLocation];
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = YourMapView.userLocation.location.coordinate.latitude;
zoomLocation.longitude= YourMapView.userLocation.location.coordinate.longitude;
// 2
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*1609.344, 0.5*1609.344);
// 3
[YourMapView setRegion:viewRegion animated:YES];
}
I needed to listen to changes for the user location. Because in the view didload the location isn't known.
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
MKCoordinateRegion region;
region.center = self.mapView.userLocation.coordinate;
MKCoordinateSpan span;
span.latitudeDelta = 1; // Change these values to change the zoom
span.longitudeDelta = 1;
region.span = span;
[self.mapView setRegion:region animated:YES];
}
and this in the viewdidload:
[self.mapView.userLocation addObserver:self
forKeyPath:#"location"
options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
context:nil];

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

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

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.

Resources