当前位置返回 0

Current Location returning 0

我正在开发的 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);
}

放在下面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

参考这个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);
}

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

并查看 'Status' 值如何变化。