【问题标题】:Current Location returning 0当前位置返回 0
【发布时间】:2015-05-30 02:35:21
【问题描述】:

我正在开发的 Xcode 应用程序需要获取用户 iOS 设备的纬度和经度。虽然目前我得到的两个值都是 0。它不要求获得该位置的许可,而且我使用的是真实设备而不是模拟器。

NSLocationAlwaysUsageDescription 在我的 info.plist 中

我还导入了 CoreLocation 并在我的 .h 文件中

@interface LocationViewController : UIViewController <CLLocationManagerDelegate>

在我的 .m 文件中

@interface LocationViewController () <CLLocationManagerDelegate>

这是我的代码:

@implementation LocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getCurrentLocation];
}

-(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)getCurrentLocation{
    CLLocationCoordinate2D coordinate = [self getLocation];
    NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude];
    NSLog(@"Latitude  = %@", latitude);
    NSLog(@"Longitude = %@", longitude);
}

【问题讨论】:

  • 哪个iOS?我相信您正在测试 iOS 8 及更高版本...对吗?
  • 是的 iOS 8.2,谢谢 :)

标签: objective-c core-location


【解决方案1】:

请参阅此answer。希望,这会有所帮助。

进行此更改:

-(CLLocationCoordinate2D) getLocation{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager requestWhenInUseAuthorization];
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
{
     NSLog(@"Status : %d", status);
}

转到设置>隐私>位置>您的应用>始终

并查看“状态”值如何变化。

【讨论】:

  • 完美!如何让应用请求位置权限,这样我就不必在设置中更改它?
  • 在 info.plist 中添加“NSLocationAlwaysUsageDescription”。
【解决方案2】:

放在startUpdatingLocation之前的下面

#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER) {
     // Use one or the other, not both. Depending on what you put in info.plist
    [self.locationManager requestWhenInUseAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];

同时在 viewDidLoad 和 viewDidAppear 中调用 [self getCurrentLocation];

它会起作用的。

还要确保您在 info.plist 文件中也有 requestWhenInUseAuthorization 的条目。

check this for more info

【讨论】:

  • 试了一下,if 语句出错。我注释掉了 if 语句并保留了 [self.locationManager requestWhenInUseAuthorization];但仍然返回 0。也像你所说的那样放在 viewdidload/viewdidappear
  • @DanWinter-Wijntjes : 检查here 我在做什么......它会工作......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-05
  • 1970-01-01
相关资源
最近更新 更多