Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CLLocationManager never calls delegate methods [duplicate]

Hi I'm playing around with locations on iPhone and right from the start I ran into problems. I've localized my problem and determined it's CLLocationManager that's bugging me.

So I developed very simple application. I just have a view controller with a CLLocationManager in it. On view did load I initialize CLLocationManager and start updating. I've also implemented two methods didFailWithError and didUpdateToLocation.

I've read a lot of questions and what i have learned so fare is this. You have to retain CLLocationManager during initialization. Also it's wise to set CLLocationManagers delegate to nil during unloading of a view (something to do with messages passing to CLLocationManager because framework retains it and it's never properly release)

All in all I just cant find a decent explanation on what to do and how to make it work.

Here's my code so if anybody could figure it out I would appreciate it. viewControllers header file

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface CoreLocationViewController : UIViewController <CLLocationManagerDelegate>
{
    CLLocationManager *locManager;
}

@property (nonatomic, retain) CLLocationManager *locManager;

@end

viewController .m file

#import "CoreLocationViewController.h"


@implementation CoreLocationViewController
@synthesize locManager;

- (void)viewDidLoad 
{
    [super viewDidLoad];

    self.locManager = [[CLLocationManager alloc] init];
    locManager.delegate = self;
    [self.locManager startUpdatingLocation];

    self.view.backgroundColor = [UIColor grayColor];
}

#pragma mark -
#pragma mark Location Delegate

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
        NSLog(@"in fail with error");
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"in update to location");
}


#pragma mark -
#pragma mark Memory Management

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload 
{
self.locManager.delegate = nil;
    [super viewDidUnload];
}


- (void)dealloc 
{
    [locManager release];
        [super dealloc];
}


@end

BTW: I'm using iOS 4.2. I'm pointing this out because I read that Apple has changed location delegates in iOS 4

like image 300
paxx Avatar asked May 10 '11 21:05

paxx


1 Answers

In my case, the delegate never gets called because of threading problem

  • the thread that operates LocationManager must have an NSRunLoop set up
  • if you use main thread, you already have a runloop, now you just need to instantiate the manager and use it on main thread

Read this to know more about CLLocationManagerDelegate

like image 111
Bùi Thanh Hải Avatar answered Oct 30 '22 10:10

Bùi Thanh Hải