从位置类向ViewController发送坐标信息

时间:2016-06-24 03:44:29

标签: ios objective-c location

我正在尝试编写一个可以更新设备位置的应用。

我设置了一个GPS_Obtainer类,它将获取设备的位置。和GPS_Obtainer类将位置信息转发给视图控制器。

我尝试使用协议,但失败了。

最好的方法是什么?如何?

1 个答案:

答案 0 :(得分:1)

您可以选择使用全部三个NotificationObserversProtocol来发送位置更新,我正在演示协议方式,请参阅下文

首先,您可以为Singleton课程创建GPS_Obtainer,如下所示。

<强> GPS_Obtainer.h

#import "GPS_Obtainer.h"

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

@protocol GPS_ObtainerDelegate <NSObject>

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

@end

@interface GPS_Obtainer : NSObject

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

+ (GPS_Obainer*)sharedSingleton;

@end

<强> GPS_Obtainer.m

@interface GPS_Obtainer()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager* locationManager;

@end

@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];
      }

}

@end

然后你只需要在ViewController中设置类的委托,它将接收它,如下所示

<强> ViewController.m

-(void)viewDidLoad{
     [[GPS_Obtainer sharedSingleton] setDelegate:self];
}

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

-(void)dealloc{
  [[GPS_Obtainer sharedSingleton] setDelegate:nil];
}

希望以上有所帮助。

干杯。