目标C - CLLocationManager找出何时点击“允许”或“不允许”
当执行CLLocationManager时,是否有一个委托方法在用户点击“允许”或“不允许”提示时被调用该请求使用位置?目标C - CLLocationManager找出何时点击“允许”或“不允许”
我试过这个,但是在用户“允许”或“不允许”之后不会调用它。
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status;
另外,是否有一个变量,会告诉我用户选择了什么?
我尝试了下面,但总是返回true。
locationManager.locationServicesEnabled
谢谢
三通
你必须实现didFailWithError:
方法:
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if ([error domain] == kCLErrorDomain) {
// We handle CoreLocation-related errors here
switch ([error code]) {
// "Don't Allow" on two successive app launches is the same as saying "never allow". The user
// can reset this for all apps by going to Settings > General > Reset > Reset Location Warnings.
case kCLErrorDenied:
case kCLErrorLocationUnknown:
default:
break;
}
} else {
// We handle all non-CoreLocation errors here
}
}
编辑:看着CLLocationManager的参考,我发现这一点:
+ (CLAuthorizationStatus)authorizationStatus
返回值 指示应用程序是否被授权 以使用位置服务的值。
讨论给定应用程序的授权状态由系统管理 并由多个因素决定。应用程序必须是 明确授权用户使用位置服务,而 位置服务目前必须为系统启用。 当您的应用程序 首次尝试使用位置服务时,此授权会自动进行。
[CLLocationManager locationServicesEnabled]
只会告诉您位置服务是否在设备上启用。
[CLLocationManager authorizationStatus]
返回您正在寻找的实际状态。
有针对
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized) {
// user allowed
}
}
中有NSLocationAlwaysUsageDescription或NSLocationWhenInUseUsageDescription项,感谢Peter。有了这个,一种方法可以添加[[NSNotificationCenter defaultCenter] postNotificationName:kLocationManagerUserDidEnableMonitoring object:nil]; [NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleLocationEnabled)name:kLocationManagerUserDidEnableMonitoring object:nil]; – dandan
locationManager.locationServicesEnabled
的委托方法指示位置服务是否可用,但并不一定意味着他们允许你的应用程序。
使用CLLocationManager.authorizationStatus()
,如果你需要找出在某个时间点的状态,或执行,因为iOS的8
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status;
拿笔记,授权请求不会自动发生,当你的应用程序第一次尝试使用位置服务。在您拨打CLLocationManager
实例前,您需要明确致电requestWhenInUseAuthorization()
,然后致电startUpdatingLocation()
。
并确保您拥有Info.plist中的NSLocationAlwaysUsageDescription
或NSLocationWhenInUseUsageDescription
密钥,具体取决于您所使用的授权类型。如果缺少这些信息,就没有错误,没有日志,没有提示,没有任何东西会指向正确的方向:)
感谢恩德。但是当你点击按钮时看起来不像这个方法被调用?看起来只有在尝试查找GPS失败时才被调用。你也知道一个会告诉用户是否允许或不允许的成员变量吗? – teepusink
我编辑了我的答案,看一看 – ender
从iOS 8开始,请注意这句话不再为真:“当您的应用程序首次尝试使用位置服务时,此授权会自动发生。”您需要在调用CLLocationManager上的startUpdatingLocation()之前明确调用requestWhenInUseAuthorization()。并确保您在Info.plist – squall3d