不断检查在ios中启用的位置服务
我试图制作一个应用程序,其中视图将检查位置服务是否已启用。如果未启用,则会弹出一个提示,但仍会继续搜索位置,但不会提示。一旦定位服务启用,它将继续其过程。不断检查在ios中启用的位置服务
如何做到这一点???
您可以通过这个代码查询位置服务的可用性:
MKUserLocation *userLocation = map.userLocation;
BOOL locationAllowed = [CLLocationManager locationServicesEnabled];
BOOL locationAvailable = userLocation.location!=nil;
if (locationAllowed==NO) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Location Service Disabled"
message:@"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
} else {
if (locationAvailable==NO)
[self.map.userLocation addObserver:self forKeyPath:@"location" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
}
谢谢。我会试试这个。 – khushalbokadey
但是这段代码只会在检查位置服务后检查一次。如果最初定位服务关闭,然后打开,然后用户返回到应用程序,那么应用程序将不会采取相应的行动。 – khushalbokadey
但是,每次你想检查应用程序中的服务时,都可以调用此方法。 –
添加在.h文件中INT计数器;
在你看来的viewDidLoad方法添加这个,因为它会检查每一秒ü可以增加计数器:
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(checkLocationMangerEnabled:)
userInfo:nil
repeats:YES];
counter = 0;
现在选择应该是:
-(void)checkLocationMangerEnabled:(id)sender
{
if([CLLocationManager locationServicesEnabled])
{
//here location is enabled
}
else
{ //Not enabled
if(counter == 60) // alert will showed in every 1 min u can increase or decrese
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Location Service Disabled"
message:@"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
counter++;
}
}
你不能继续获得,如果位置的位置服务被禁用。
如果要继续检查
[CLLocationManager locationServicesEnabled]
如果启用搜索位置确保该服务允许,开始更新位置
[locationManager startUpdatingLocation];
然后在
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
[locationManager stopUpdatingLocation]; // This will stop to check the location
}
删除此代码仍然检查位置[locationManager stopUpdatingLocation];
,但这不是t他最好的办法,一定要阅读apple documentation for the policy of getting the location
如果您发现它有用并能解决您的问题,请接受答案。 – Raptor