我正在开发的我的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);
}
答案 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
。
答案 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;总是
了解“状态”值如何变化。