Nan Nan - 7 months ago 21
Objective-C Question

Send Coordinate info to ViewController from a location class

I am trying to write an app, which can update device's locations.

I set up a GPS_Obtainer Class, which will obtain device's location. and GPS_Obtainer class will forward the location info to a view controller.

I tried to use protocol, but it failed.

What is the best way to do it? and how?


You can choose to use all three be it Notification, Observers, or Protocol to send location updates, I am demonstrating Protocol way, see below

First you can create a Singleton for your GPS_Obtainer class like below.


#import "GPS_Obtainer.h"

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

@protocol GPS_ObtainerDelegate <NSObject>

-(void)locationDidUpdated:(CLLocation *)location;


@interface GPS_Obtainer : NSObject

@property (nonatomic, strong) id<GPS_ObtainerDelegate> delegate;

+ (GPS_Obainer*)sharedSingleton;



@interface GPS_Obtainer()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager* locationManager;


@implementation GPS_Obtainer

- (id)init {
    self = [super init];

    if(self) {
        self.locationManager = [CLLocationManager new];
        [self.locationManager setDelegate:self];
        [self.locationManager startUpdatingLocation];

    return self;

+ (GPS_Obtainer*)sharedSingleton {

    static GPS_Obtainer *sharedSingleton = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
       sharedSingleton = [GPS_Obtainer new];
    return sharedSingleton;

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

      if(self.delegate && [self.delegate respondsToSelector:@selector(locationDidUpdated:)]){
            [self.delegate locationDidUpdated:newLocation];



Then you just need to set delegate of the class in ViewController which will receive it like below


     [[GPS_Obtainer sharedSingleton] setDelegate:self];

-(void)locationDidUpdated:(CLLocation *)location{
    //HERE you get the location updates

  [[GPS_Obtainer sharedSingleton] setDelegate:nil];

Hope above helps.