我如何检查是否位置服务是为我的应用程序启用?
我有2个故事板,我想检查位置服务。 如果我的应用程序定位功能的服务,我想推出的地图故事板带的位置。 否则,我想启动另一个故事板。 我该怎么办编程?
我如何检查是否位置服务是为我的应用程序启用?
我有2个故事板,我想检查位置服务。 如果我的应用程序定位功能的服务,我想推出的地图故事板带的位置。 否则,我想启动另一个故事板。 我该怎么办编程?
这是正确的。
if ([CLLocationManager locationServicesEnabled]){
NSLog(@"Location Services Enabled");
if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){
alert = [[UIAlertView alloc] initWithTitle:@"App Permission Denied"
message:@"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}
经测试在iOS 9.2
为了得到位置更新,我们应经常检查
并启动正确的设置屏幕上用户启用
启动iOS设备位置设置页面
STEP.1转到项目设置 - >信息 - > URL类型 - >添加新的URL方案
下面的代码使用Step.2推出直拨电话的位置设置页面:(注:URL方案是iOS中不同10+,我们检查版本说明这里 )
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice
currentDevice] systemVersion] compare:v options:NSNumericSearch] ==
NSOrderedAscending)
//Usage
NSString* url = SYSTEM_VERSION_LESS_THAN(@"10.0") ? @"prefs:root=LOCATION_SERVICES" : @"App-Prefs:root=Privacy&path=LOCATION";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: url]];
启动应用程序的位置设置页面
使用下面的代码来直接启动应用程序的位置设置页面
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
以下是完整的代码示例:
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice
currentDevice] systemVersion] compare:v options:NSNumericSearch] ==
NSOrderedAscending)
CLLocationManager *locationManager;
-(void) checkLocationServicesAndStartUpdates
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
{
[locationManager requestWhenInUseAuthorization];
}
//Checking authorization status
if (![CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled!"
message:@"Please enable Location Based Services for better results! We promise to keep your location private"
delegate:self
cancelButtonTitle:@"Settings"
otherButtonTitles:@"Cancel", nil];
//TODO if user has not given permission to device
if (![CLLocationManager locationServicesEnabled])
{
alertView.tag = 100;
}
//TODO if user has not given permission to particular app
else
{
alertView.tag = 200;
}
[alertView show];
return;
}
else
{
//Location Services Enabled, let's start location updates
[locationManager startUpdatingLocation];
}
}
处理用户输入反应的点击,并启动正确的位置设置
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0)//Settings button pressed
{
if (alertView.tag == 100)
{
//This will open ios devices location settings
NSString* url = SYSTEM_VERSION_LESS_THAN(@"10.0") ? @"prefs:root=LOCATION_SERVICES" : @"App-Prefs:root=Privacy&path=LOCATION";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: url]];
}
else if (alertView.tag == 200)
{
//This will opne particular app location settings
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
}
else if(buttonIndex == 1)//Cancel button pressed.
{
//TODO for cancel
}
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(@"%@",error.userInfo);
if([CLLocationManager locationServicesEnabled]){
NSLog(@"Location Services Enabled");
if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"App Permission Denied"
message:@"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}
}
这背后的原因,这种方法会打电话的时候,你的服务将禁用定位服务。 此代码对我来说非常有用。
检查CLLocationManager的locationServicesEnabled属性来检查全系统的可用性。 用你的CLLocationManagerDelegate的的LocationManager:didFailWithError:方法并检查是否有kCLErrorDenied错误,看看如果用户拒绝定位服务。
BOOL locationAllowed = [CLLocationManager locationServicesEnabled];
if (!locationAllowed)
{
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];
}
为您的应用程序使用此代码
- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
// Set a movement threshold for new events.
locationManager.distanceFilter = 500;
[locationManager startUpdatingLocation];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// If it's a relatively recent event, turn off updates to save power
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"%@",error);
}
如果位置服务禁用您的应用程序,然后它给你错误
Error Domain=kCLErrorDomain Code=1 "The operation couldn’t be completed. (kCLErrorDomain error 1.)"
经过大量的调查。 我建议,以显示不上的警报视图的标签上,并此消息。 因为,有很多情况下,再次进行测试的(用户禁用一般或只是应用定位服务。删除应用程序,重新安装)。
其中一个案例引起您的警报与在同一时间苹果的警告消息一起显示您的消息。 您的警报会落后于苹果的警觉。 这是一个令人困惑和未逻辑行为。
我提出以下建议:
斯威夫特3:
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
Log.verbose("User still thinking granting location access!")
manager.startUpdatingLocation() // this will access location automatically if user granted access manually. and will not show apple's request alert twice. (Tested)
break
case .denied:
Log.verbose("User denied location access request!!")
// show text on label
label.text = "To re-enable, please go to Settings and turn on Location Service for this app."
manager.stopUpdatingLocation()
loadingView.stopLoading()
break
case .authorizedWhenInUse:
// clear text
label.text = ""
manager.startUpdatingLocation() //Will update location immediately
break
case .authorizedAlways:
// clear text
label.text = ""
manager.startUpdatingLocation() //Will update location immediately
break
default:
break
}
}
Objective-C的:
- (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
switch (status) {
case kCLAuthorizationStatusNotDetermined: {
DDLogVerbose(@"User still thinking granting location access!");
[locationManager startUpdatingLocation]; // this will access location automatically if user granted access manually. and will not show apple's request alert twice. (Tested)
} break;
case kCLAuthorizationStatusDenied: {
DDLogVerbose(@"User denied location access request!!");
// show text on label
label.text = @"To re-enable, please go to Settings and turn on Location Service for this app.";
[locationManager stopUpdatingLocation];
[loadingView stopLoading];
} break;
case kCLAuthorizationStatusAuthorizedWhenInUse:
case kCLAuthorizationStatusAuthorizedAlways: {
// clear text
label.text = @"";
[locationManager startUpdatingLocation]; //Will update location immediately
} break;
default:
break;
}
}
最好的办法,处理所有的情况下! - >
//First, checking if the location services are enabled
if(![CLLocationManager locationServicesEnabled]){
[self showMessage:@"Please enable location services to detect location!" withTitle:@"Location not enabled"];
}
else if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){
//Now if the location is denied.
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:@"Enable location permission"
message:@"To auto detect location, please enable location services for this app"
preferredStyle:UIAlertControllerStyleAlert];
alertController.view.tintColor = AppColor;
UIAlertAction *cancelAction = [UIAlertAction
actionWithTitle:@"Dismiss"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
NSLog(@"Cancel action");
}];
UIAlertAction *goToSettings = [UIAlertAction
actionWithTitle:@"Settings"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
//Simple way to open settings module
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:url];
}];
[alertController addAction:cancelAction];
[alertController addAction:goToSettings];
[self presentViewController:alertController animated:YES completion:^{
alertController.view.tintColor = AppColor;
}];
}
else{
//Do whatever you want here
}
迅速3.0和iOS 10解决方案:
self.locationManager?.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() != CLAuthorizationStatus.denied {
locationManager?.delegate = self
locationManager?.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager?.distanceFilter = distanceFiler
locationManager?.startUpdatingLocation()
}else{
let alertView = UIAlertView(title: "Location Services Disabled!", message: "Please enable Location Based Services for better results! We promise to keep your location private", delegate: self, cancelButtonTitle: "Settings", otherButtonTitles: "Cancel")
alertView.delegate = self
alertView.show()
return
}
@objc(alertView:clickedButtonAtIndex:) func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
if buttonIndex == 0 {
if let url = URL(string: "App-Prefs:root=LOCATION_SERVICES") {
UIApplication.shared.open(url, completionHandler: .none)
}
}
else if buttonIndex == 1 {
//TODO for cancel
}
}