【问题标题】:Where to store app location data?应用位置数据存储在哪里?
【发布时间】:2015-05-20 11:11:16
【问题描述】:

我有一个应用需要在设备打开时检索设备的经度/纬度坐标,然后使用这些坐标与服务器通信。我的应用基于UITabBarController 所以有不同的页面,其中一些需要使用这个位置数据。我还需要在其中一些页面上实现拉取刷新。

我需要知道的是:我应该在哪里存储位置坐标以及我应该在哪里实现CLLocationManager?我应该在每个需要位置的类中都有一个位置管理器,还是应该在应用程序委托中?

谢谢

【问题讨论】:

  • 你可以继承UITabbarViewController类,并从中获取用户位置。
  • 您可以在 controller-layer 上创建一个单例,它会自行更新位置的值,并在运行时需要时随时从该类中读取当前值。小菜一碟。

标签: ios objective-c swift core-location cllocationmanager


【解决方案1】:

只需创建一个单例位置管理器类(例如,MyLocationManager)。您的.h 文件可能如下所示:

@interface MyLocationManager : NSObject <CLLocationManagerDelegate>

@property (strong, nonatomic) CLLocation *currentLocation;

+ (id)sharedInstance;

- (void)updateCurrentLocation;

@end

然后在.m文件中实现方法:

#import "MyLocationManager.h"

@interface MyLocationManager ()

@property (strong, nonatomic) CLLocationManager *locationManager;

@end

@implementation MyLocationManager

#pragma mark - Singleton methods

+ (id)sharedInstance {
    static dispatch_once_t token;
    static id shared = nil;
    dispatch_once(&token, ^{
        shared = [[super alloc] initUniqueInstance];
    });

    return shared;
}

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

    if (self) {
        self.locationManager = [[CLLocationManager alloc] init];
        [self.locationManager setDesiredAccuracy:kCLLocationAccuracyKilometer];
        self.locationManager.delegate = self;
    }

    return self;
}

#pragma mark - Public methods

- (void)updateCurrentLocation {
    [self.locationManager startUpdatingLocation];
}

@end

实现委托方法并在获得更新后的值时更新currentLocation 属性。我还建议在某处检查地理位置权限并做出适当反应。请记住,您应该使用通知(NSNotificationCenter)来通知其他对象有关单例属性的更新,而不是委托(通常,您不应该将单例绑定到任何对象)。祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 2015-01-22
    相关资源
    最近更新 更多