I am trying to get the user's current location on multiple controller, they are part of navigation controller, tabbarcontroller, presentmodel controller, so basically I really cannot do something like self.navigationcontroller or self.tabBarController.
What i did was I created a LocationHelper and a LocationHelperDelegate
@protocol LocationHelperDelegate
@required
- (void)locationUpdate:(CLLocation *)location; // Our location updates are sent here
- (void)locationError:(NSError *)error; // Any errors are sent here
@end
@interface LocationHelper : NSObject <CLLocationManagerDelegate>{
CLLocationManager *locationManager;
CLLocation *currentLocation;
id delegate;
}
@property (nonatomic, retain) CLLocation *currentLocation;
@property (nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, assign) id delegate;
@end
And then in my .m file I do the following
-(id) init {
self = [super init];
if(self != nil){
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation
*)newLocation fromLocation:(CLLocation *)oldLocation {
if([self.delegate conformsToProtocol:@protocol(LocationHelperDelegate)]) {
[self.delegate locationUpdate:newLocation];
}
}
And then now this is what I am doing in all my controller where I need a location update. In the init method
LocationHelper* locationHelper = [[LocationHelper alloc]init];
locationHelper.delegate = self;
[locationHelper.locationManager startUpdatingLocation];
and then I implement
- (void)locationUpdate:(CLLocation *)location {
latitude = location.coordinate.latitude;
longitude = location.coordinate.longitude;
[locationHelper.locationManager stopUpdatingLocation];
}
I am 100% sure this is not the right way for doing it, but I have no clue how I should be doing this. Basically all I need is to do startUpdatingLocation once and then all my controller get a notification for locationUpdate, and when every one has received the notification stopUpdatingLocation.
I was thinking about making the LocationHelper class has a singleton but then when all the controller gets the instance of it can they set them self as a delegate, that doesn't seems right because delegate is one of the instance variable in the LocationHelper and it can hold only one value.
So as you can see I am confused, please help.