即使不需要,CLLocationManager仍然存在

时间:2013-06-06 11:57:06

标签: ios objective-c cocoa-touch cllocationmanager

我的应用中有一个映射功能。它属于Tab Bar控制器选项卡之一。

我遇到的问题是应用程序在启动后立即要求位置权限。 我不想打扰用户的位置相关问题,直到他真正去了应用程序的地图部分。

如果我理解得当,位置管理员在我实例化之前不应该费心去问。此外,只要用户离开应用程序的地图部分,通过选择其他选项卡或按主页按钮即可。我没有位置管理器。

为什么这么快就要求呢?我的问题是在这个特殊情况下是否有一些特殊规则......或者它是由我的应用程序设计缺陷造成的?

3 个答案:

答案 0 :(得分:2)

我会选择“流动的应用程序设计”。你没有显示任何代码,所以很难说,但是UITabBarController一次实例化它的所有View控制器,所以你的CCLocation类可能正在用你的TabBar进行初始化。

您可以做的是:仅在您实际使用它的View Controller上的-viewWillAppear方法初始化您的CCLocation内容。

答案 1 :(得分:1)

你可以写这样的东西。

H:

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

@interface LocationController : NSObject <CLLocationManagerDelegate> {
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
} 

+ (LocationController *)sharedInstance;
- (void)start;
- (void)stop;

@property (nonatomic, strong) CLLocation *currentLocation;

@end

米:

#import "LocationController.h"

@implementation LocationController

static LocationController *sharedInstance;

+ (LocationController *)sharedInstance {
    static LocationController *sharedClient;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedClient = [[LocationController alloc] init];
    });
    return sharedClient;
}

-(id) init {
    if (self = [super init]) {
        currentLocation = [[CLLocation alloc] init];
        locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;
        [self start];
    }
    return self;
}

- (void)start {
    [locationManager startUpdatingLocation];
}

- (void)stop {
    [locationManager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *loc = [locations lastObject];

    if ( abs([loc.timestamp timeIntervalSinceDate: [NSDate date]]) < 120) {
        self.currentLocation = loc;
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"%@", error);
}

@end

然后,只要您需要找到,您就可以执行以下操作:

[[LocationController sharedInstance] start];

答案 2 :(得分:0)

你在哪里实例化CLLocationManager?在实例化选项卡栏控制器时实例化所有视图控制器时,在您转到相关选项卡之前不会创建它们各自的视图。因此,如果您在控制器的CLLocationManager方法之一中实例化init,那么将在控制器(即实例化标签栏控制器时)时创建该位置管理器。但是,如果您在viewDidLoad中具有位置管理器的实例化,则在您单击相应的选项卡之前不应对其进行实例化。