jerik
jerik

Reputation: 5767

objective-c getting location and notifiy if updated. observer? how?

I use the locationmanger to get my current location on the iPhone.

#pragma mark - Location handling
-(void)doLocation {
    self.locationManager = [[CLLocationManager alloc] init];
    [...]
    SingletonClass *sharedSingleton = [SingletonClass sharedInstance];
    sharedSingleton.coordinate = [location coordinate];
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    [...]
    SingletonClass *sharedSingleton = [SingletonClass sharedInstance];
    [sharedSingleton setCoordinate:CLLocationCoordinate2DMake(currentLat, currentLng)];

    NSLog(@"debug: self.currentLoc: %@", self.currentLoc);

}

this works fine, I get the location coordinates with some delay and can access them via the sharedSingleton. When I have the coordinates, I have to trigger another function which needs the coordinates as parameter.

And here my issue starts...

How do I now, when the coordinates are retrieved and I can call the other function which needs the coordinates as input parameters. Is there a kind of observer that I could use? If, how do I implement this?

I just need something that tells me: hey dude, the coordinates are available for use, so that I can trigger the next function..

Upvotes: 0

Views: 175

Answers (2)

rmonjo
rmonjo

Reputation: 2745

You can use the NSNotificationCenter or a delegate. Delegate pattern in objective C is really common. For that you will need to implement a protocol in your .h file, something like this:

@protocol MyLocationManagerDelegate <NSObject>
- (void) locationManager:(MyLocationManager *)manager didFindLocation:(CCLocation*) location
@end

//still in your .h file add a delegate that implements this protocol
@property (nonatomic, assign) id<MyLocationManagerDelegate> delegate

Then in the other class that must take the action when coordinates are found, indicates that it implements the MyLocationManagerDelegate protocol, and implement the - (void) locationManager:(MyLocationManager *)manager didFindLocation:(CCLocation*) location method.

After allocating your location manager set your other class as the delegate. And in your didUpdateToLocation method simply call [self.delegate locationManager:self didFindLocation:self.currentLoc]

Upvotes: 1

Eric
Eric

Reputation: 4395

One way to achieve this functionality is NSNotificationCenter.

This post will show you how to set up a notification through NSNotificationCenter.

Send And Recieve Messages Through NSNotificationCenter In Objective-c

Upvotes: 0

Related Questions