CLLocation当前位置不起作用
我在我的类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]; } }
但我没有获得允许访问的位置或popup窗口。
我正在使用核心位置框架。
在button上单击我打印标签中的纬度,经度和地址。
我正在模拟器上testing这个。
有时候,模拟器不能使用启用位置的服务使用Apple Device
进行完美的testing。
在您的info.plist
文件中添加以下密钥以允许访问popup窗口。
或者将它们添加为更新info.plist
文件的源代码。
<key>NSLocationAlwaysUsageDescription</key> <string>message for location uses</string> <key>NSLocationWhenInUseUsageDescription</key> <string>message for location uses</string>
试试这个代码在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键的string添加到应用程序的Info.plist中。
locationManager =[[CLLocationManager alloc] init]; [locationManager requestWhenInUseAuthorization]; locationManager.delegate=self; locationManager.desiredAccuracy=kCLLocationAccuracyBest; [locationManager startUpdatingLocation];
你可以添加你的plist:
<key>NSLocationAlwaysUsageDescription</key> <key>NSLocationWhenInUseUsageDescription</key>