不断检查ios中启用的位置服务

时间:2012-06-16 09:17:25

标签: iphone objective-c ios5

我正在尝试创建一个应用程序,其中视图将检查位置服务是否已启用。如果它没有启用,那么它会提示弹出一个但仍然会继续搜索位置但不提示。一旦启用了位置服务,它将继续其过程。

怎么做???

3 个答案:

答案 0 :(得分:1)

如果禁用了位置服务,则无法继续获取该位置。

如果要继续搜索位置,请确保通过选中

启用该服务
[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];,但这不是最佳方法,请务必阅读apple documentation for the policy of getting the location

答案 1 :(得分:0)

您可以通过以下代码查看位置服务的可用性:

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];
    }

答案 2 :(得分:0)

添加.h文件int counter;

在你的视图的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++;
   }
}