0

I am new to iOS development and trying to build an app that uses user location in multiple view controllers. I am trying to implement the location manager in one separate class, and then send the location from the call back function to the view controllers, whenever there is a new location available. I have seen an implementation that uses singleton but wanted to use protocol methods instead - I have seen in the past such an example, which I can't find anymore, and it worked really well.

Could people advise on what's the best way to design it in such a way? Here are some key parts from one of my view controllers and the location manager class, for reference.

ViewController.m

- (void)viewDidLoad {

locMan = [[LocClass alloc] init]; 
[locMan startLocationManager]; 
...
}

LocClass.m (the location manager class)

 - (void)startLocationManager {
 [self.coreLocationManager startUpdatingLocation];
 }

 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
 //the usual stuff here...
}

How could I use protocol methods to send back the location from didUpdateLocations: to ViewController.m when it's available? Referencing an example would be great if possible.

moshikafya
  • 3,190
  • 5
  • 22
  • 27
  • PS: I have seen this example, but as I explained, this is not what I am looking for: http://stackoverflow.com/questions/11513259/ios-cllocationmanager-in-a-separate-class since it uses singleton. – moshikafya Apr 08 '17 at 04:45

1 Answers1

1

In LocClass.h file add the protocol method

@protocol LocationUpdateProtocol <NSObject>
@optional
// Override this method in UIViewController derived class to get back the location details.
-(void)locationUpdatedWithManager:(CLLocationManager *)manager newLocations:(NSArray *)locations;
@end

@interface LocClass : NSObject
@property (nonatomic, weak) NSObject<LocationUpdateProtocol> *delegate;
@end

Then in your .m file

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
 //the usual stuff here...

   if([self.delegate conformsToProtocol:@protocol(LocationUpdateProtocol)] && [self.delegate respondsToSelector:@selector(locationUpdatedWithManager:newLocations:)]) {
        [self.delegate locationUpdatedWithManager:manager newLocations:locations];
    }
}

Now the mainViewcontroller class should implement this Protocol

@interface ViewController () <LocationUpdateProtocol>

And the place where you initilaze location manager class, set the delegate

- (void)viewDidLoad {

locMan = [[LocClass alloc] init]; 
[locMan startLocationManager]; 
locMan.delegate = self;
...
}

//Will get the delegate callback here.
 - (void)locationUpdatedWithManager:(CLLocationManager *)manager newLocations:(NSArray *)locations{
}
Jen Jose
  • 3,995
  • 2
  • 19
  • 36