1

我正在使用 UISwitch 打开和关闭位置服务。当我“打开” UISwitch 时,位置服务开始跟踪位置。我可以拿出应用程序,位置服务运行良好。我的问题是当我切换“关闭”跟踪并移动到任何View Controller仍处于“开启”状态的位置跟踪并且它没有停止跟踪时。下面是我的代码。

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation* location = [locations lastObject];
    latDeg = location.coordinate.latitude;
    longDeg = location.coordinate.longitude;
}

-(IBAction)startTracking:(id)sender{
 if(startTrackingButton.on){
[locationManager startUpdatingLocation];
[[NSUserDefaults standardUserDefaults] setBool:startTrackingButton.on forKey:@"switchValue"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
else{
    [[NSUserDefaults standardUserDefaults] setBool:startTrackingButton.on forKey:@"switchValue"];
  [[NSUserDefaults standardUserDefaults] synchronize];
  [locationManager stopUpdatingLocation];
 }
}

- (void)viewDidLoad{
   [super viewDidLoad];
   [startTrackingButton setOn:[[NSUserDefaults standardUserDefaults] boolForKey:@"switchValue"]];
   locationManager = [[CLLocationManager alloc] init];
   [locationManager setDelegate:self];
   [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
   [self.navigationItem setHidesBackButton:YES];
}

有什么建议么?

4

1 回答 1

0

我将假设这startTrackingButton实际上是一个UISwitch. 如果是这种情况,您应该检查isOn财产。

if (startTrackingButton.isOn) {
    [locationManager startUpdatingLocation];
    [[NSUserDefaults standardUserDefaults] setBool:startTrackingButton.on forKey:@"switchValue"];
    [[NSUserDefaults standardUserDefaults] synchronize];
} else {
    [[NSUserDefaults standardUserDefaults] setBool:startTrackingButton.on forKey:@"switchValue"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [locationManager stopUpdatingLocation];
}
于 2013-09-17T18:40:56.947 回答