【问题标题】:CLLocationManager weird behaviorCLLocationManager 奇怪的行为
【发布时间】:2013-08-09 10:46:34
【问题描述】:

我有一个奇怪的问题。

我有 2 节课:

  1. 商业风险投资
  2. 收藏夹VC

在他们两个中,我都会向用户显示他到某个特定点的当前距离。 在这两个类中,我使用完全相同的代码。

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);
}

【问题讨论】:

  • viewWillAppear 中调用[self locatedMe]; 而不是在viewDidLoad 中。

标签: ios objective-c gps location cllocationmanager


【解决方案1】:

好的!通过使用此代码在主线程上运行代码来修复此问题:

-(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];
     });

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    相关资源
    最近更新 更多