我正在尝试在我的iOS应用中获取用户位置。首先,我在项目中包含了corelocation框架。然后在一个按钮上单击“我正在调用核心位置api”,如下所示。当我尝试将其安装在设备中时,核心位置从不询问用户权限。当我尝试单击按钮获取位置时,我将kCLAuthorizationStatusNotDetermined定义为authorisationStatus。请帮助我。我不知道发生了什么事。
- (IBAction)fetchLessAccurateLocation:(id)sender {
[self.txtLocation setText:@""];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
locationManager.distanceFilter = 1000;
if ([self shouldFetchUserLocation]) {
[locationManager startUpdatingLocation];
}
}
这是我的shouldFetchUserLocation方法:
-(BOOL)shouldFetchUserLocation{
BOOL shouldFetchLocation= NO;
if ([CLLocationManager locationServicesEnabled]) {
switch ([CLLocationManager authorizationStatus]) {
case kCLAuthorizationStatusAuthorized:
shouldFetchLocation= YES;
break;
case kCLAuthorizationStatusDenied:
{
UIAlertView *alert= [[UIAlertView alloc]initWithTitle:@"Error" message:@"App level settings has been denied" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
alert= nil;
}
break;
case kCLAuthorizationStatusNotDetermined:
{
UIAlertView *alert= [[UIAlertView alloc]initWithTitle:@"Error" message:@"The user is yet to provide the permission" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
alert= nil;
}
break;
case kCLAuthorizationStatusRestricted:
{
UIAlertView *alert= [[UIAlertView alloc]initWithTitle:@"Error" message:@"The app is recstricted from using location services." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
alert= nil;
}
break;
default:
break;
}
}
else{
UIAlertView *alert= [[UIAlertView alloc]initWithTitle:@"Error" message:@"The location services seems to be disabled from the settings." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
alert= nil;
}
return shouldFetchLocation;
}
这是我的核心位置委托方法:
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_6_0){
NSLog(@"location fetched in delegate");
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0) {
// If the event is recent, do something with it.
NSLog(@"inside loop.... latitude %+.6f, longitude %+.6f\n",
location.coordinate.latitude,
location.coordinate.longitude);
}
NSLog(@"latitude %+.6f, longitude %+.6f\n",
location.coordinate.latitude,
location.coordinate.longitude);
[self.txtLocation setText:[NSString stringWithFormat:@"\nlatitude: %+.6f \nlongitude: %+.6f", location.coordinate.latitude, location.coordinate.longitude]];
[locationManager stopUpdatingLocation];
[locationManager stopMonitoringSignificantLocationChanges];
if(locationManager!=nil){
locationManager.delegate= nil;
locationManager= nil;
}
}