尝试仅在启用位置服务导致无限循环时运行代码

时间:2013-07-08 19:05:38

标签: ios objective-c cllocationmanager

我的应用程序需要位置服务,我希望只在第一次打开应用程序或之前启用时启用我的主要方法。

我使用以下代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([CLLocationManager authorizationStatus] == YES) {
        //are enabled, run the JSON request
        [self getDataFromJson];
    } else {
        //is not enabled, so set it up
        NSLog(@"no");
        [locationManager location];
    };

}

-(CLLocationCoordinate2D) getLocation{

    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];
    CLLocation *location = [locationManager location];
    CLLocationCoordinate2D coordinate = [location coordinate];
    return coordinate;

}

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusDenied) {
        //location denied, handle accordingly
        locationFailView.hidden = NO;
        mainView.hidden = YES;
    }
    else if (status == kCLAuthorizationStatusAuthorized) {
        //hooray! begin tracking
        [self getDataFromJson];
    }
}

//class to convert JSON to NSData
- (IBAction)getDataFromJson {
    NSLog(@"running");
    CLLocationCoordinate2D coordinate = [self getLocation];
    NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude];
    ...
}

此代码现在几乎完美无缺,除了getDataForJson一次又一次地运行,导致无限循环(即,“运行”一次又一次输出)。

我怎么会出错,所以它只运行一次?

谢谢!

1 个答案:

答案 0 :(得分:2)

似乎 getDataFromJson 调用 getLocation ,它分配 locationManager 实例,其代理调用 locationManager:didChangeAuthorizationStatus:,调用 getDataFromJson 。只有在启用位置服务时才会发生这种情况,因为只有在状态== kCLAuthorizationStatusAuthorized 时才会调用 getDataFromJson

getDataFromJson - > getLocation~> locationManager:didChangeAuthorizationStatus(通过委托) - > getDataFromJson (启用位置服务时)。