我的班级ViewController
中有这段代码:
CLLocationManager *locationManager;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
[locationManager requestWhenInUseAuthorization];
}
- (IBAction)getCurrentLocation:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
-(void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"Did finish with error - %@", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Failed to get your location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(@"did Update Location - %@", newLocation);
CLLocation *currentLocation = newLocation;
if(currentLocation != nil) {
_longitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
_latitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
}
}
但我没有获得允许访问的位置或弹出窗口。
我正在使用核心位置框架。
点击按钮,我在标签中打印纬度,经度和地址。
我在模拟器上测试它。
答案 0 :(得分:2)
有时模拟器无法使用启用位置的服务,使用Apple Device
进行完美测试。
在info.plist
文件中添加以下键以获取允许访问弹出窗口。
或将它们添加为更新info.plist
文件源代码。
<key>NSLocationAlwaysUsageDescription</key>
<string>message for location uses</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>message for location uses</string>
答案 1 :(得分:1)
在viewDidLoad中尝试此代码...
//---- For getting current gps location
locationManager = [CLLocationManager new];
locationManager.delegate = self;
if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
//------
您还必须将 NSLocationAlwaysUsageDescription 或 NSLocationWhenInUseUsageDescription 键的字符串添加到应用的Info.plist中。
答案 2 :(得分:0)
locationManager =[[CLLocationManager alloc] init];
[locationManager requestWhenInUseAuthorization];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
你可以添加你的plist:
<key>NSLocationAlwaysUsageDescription</key>
<key>NSLocationWhenInUseUsageDescription</key>