CLLocationManager奇怪的行为

时间:2013-08-09 10:46:35

标签: ios objective-c gps location cllocationmanager

我有一个奇怪的问题。

我有2个班级:

  1. BusinessVC
  2. FavoritesVC
  3. 在他们两个中,我向用户显示他与某个特定点之间的当前距离。 在这两个类中,我使用完全相同的代码。

    FavoritesVC呈现为模态视图控制器。

    出于某种原因 didUpdateLocations / didUpdateToLocation 方法仅在BusinessVC中调用,而不是在FavoritesVC中调用。

    我在两个班级中实施 CLLocationManagerDelegate 委托。

    我使用的代码:

     -(void)viewDidLoad {
         [super viewDidLoad]; 
         [self locatedMe];
    }
    
    -(void) locatedMe{
        NSLog(@"locateMe");
        _locationManager = [[CLLocationManager alloc] init];
        [_locationManager setDelegate:self];
        [_locationManager setDistanceFilter:kCLDistanceFilterNone]; // whenever we move
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters]; // 100 m
        [_locationManager startUpdatingLocation];
    }
    
    
    // For iOS6
    -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray  *)locations {
    
        CLLocation * newLocation = [locations lastObject];
        NSNumber *lat = [[NSNumber alloc] initWithDouble:newLocation.coordinate.latitude];
        NSNumber *lon = [[NSNumber alloc] initWithDouble:newLocation.coordinate.longitude];
    
        self.userLocation = [[CLLocation alloc] initWithLatitude:[lat doubleValue] longitude:[lon doubleValue]];
    
    }
    
    
    // For earlier then iOS6
    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    
        NSNumber *lat = [[NSNumber alloc] initWithDouble:newLocation.coordinate.latitude];
        NSNumber *lon = [[NSNumber alloc] initWithDouble:newLocation.coordinate.longitude];
    
        self.userLocation = [[CLLocation alloc] initWithLatitude:[lat doubleValue] longitude:[lon doubleValue]];
    
        NSLog(@"%@",self.userLocation);
    }
    

1 个答案:

答案 0 :(得分:0)

OK!修复了使用以下代码在主线程上运行代码:

-(void) locateMe {
    NSLog(@"locateMe");
    dispatch_async(dispatch_get_main_queue(), ^{
         _locationManager = [[CLLocationManager alloc] init];
         [_locationManager setDelegate:self];
         [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; // 100 m
         [_locationManager startUpdatingLocation];
         [_locationManager startUpdatingHeading];
     });

}