当前位置返回0

时间:2015-03-26 06:30:53

标签: objective-c core-location

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

NSLocationAlwaysUsageDescription位于我的info.plist

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

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

2 个答案:

答案 0 :(得分: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&amp;中调用[self getCurrentLocation]; viewDidAppear两者。

它会起作用。

另外,请确保您也在info.plist文件中输入了requestWhenInUseAuthorization

check this for more info

答案 1 :(得分:2)

请参阅此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);
}

转到设置&gt;隐私&gt;位置&gt;你的应用&gt;总是

了解“状态”值如何变化。