【问题标题】:Objective C locationManager cannot get current location, always returns 0Objective C locationManager 无法获取当前位置,总是返回 0
【发布时间】:2015-05-26 14:26:07
【问题描述】:

能否请您查看以下代码,它确实尝试使用代表的 locationManager,并尝试返回设备的当前位置。

但总是返回0(允许的位置权限)

.m

self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self.locationManager startUpdatingLocation];

if(IS_OS_8_OR_LATER) {
    [self.locationManager requestAlwaysAuthorization];
}


CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

if (status == kCLAuthorizationStatusAuthorizedAlways) {
  // TODO: Handle status authorized always


} else if (status == kCLAuthorizationStatusNotDetermined) {
  // TODO: Handle status not determined


} else {
  // TODO: Handle other
}






- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

  //NSLog(@"newLocation: %@", newLocation);

}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{

    //NSLog(@"Error: %@",[error description]);

}

info.plist

<key>NSLocationAlwaysUsageDescription</key>
<string>We would like to use your location.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>We would like to use your location.</string>

【问题讨论】:

  • 你对你的 locationManager 有强引用吗?
  • 是 @property (strong, nonatomic) CLLocationManager *locationManager;在 .h 上声明
  • 返回0是什么意思?
  • 你在模拟器上运行吗?
  • didUpdateToLocation 已弃用,您应该改用 didUpdateLocations

标签: ios objective-c core-location


【解决方案1】:

请尝试在 requestAlwaysAuthorization 之后调用 startUpdatingLocation。并使用下面的 didUpdateLocations 委托方法。

if(IS_OS_8_OR_LATER) {
    [self.locationManager requestAlwaysAuthorization];
}

[self.locationManager startUpdatingLocation];


- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{

        _currentLocation = [locations objectAtIndex:0]; 
        //do your stuff with the location

    }

对于模拟器测试 - 选择模拟器并转到调试 -> 位置 -> Apple 或 City Run

对于设备测试如果您获得当前位置,请查看地图。有时设备由于在屋内而无法获取当前位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 2018-12-19
    相关资源
    最近更新 更多