The object that you use to start and stop the delivery of location-related events to your app.
- 用于启动和停止向应用程序传递与位置相关的事件的对象。
Overview
You use instances of this class to configure, start, and stop the Core Location services. A location manager object supports the following location-related activities:
- 您可以使用此类的实例来配置,启动和停止Core Location服务。 位置管理器对象支持以下与位置相关的活动:
Tracking large or small changes in the user’s current location with a configurable degree of accuracy.
- 使用可配置的准确度跟踪用户当前位置的大小变化。
Reporting heading changes from the onboard compass. (iOS only)
- 从机载罗盘报告航向变化。 (仅限iOS)
Monitoring distinct regions of interest and generating location events when the user enters or leaves those regions.
- 监控不同的感兴趣区域并在用户进入或离开这些区域时生成位置事件。
Deferring the delivery of location updates while the app is in the background. (iOS only)
- 在应用程序处于后台时推迟传递位置更新。 (仅限iOS)
Reporting the range to nearby beacons.
- 将范围报告给附近的信标。
When you are ready to use location services, follow these steps:
- 准备好使用位置服务时,请按照下列步骤操作:
- Check to see if your app is authorized to use location services and request permission if your app's authorization status is not yet determined, as described in Requesting Permission to Use Location Services.
- 检查您的应用是否有权使用位置服务,并在尚未确定您的应用的授权状态时请求许可,如请求使用位置服务的权限中所述。
Check to see if the appropriate location services are available for you to use, as described in Determining the Availability of Location Services.
检查是否有适合您使用的位置服务,如确定位置服务的可用性中所述。Create an instance of the CLLocationManager class and store a strong reference to it somewhere in your app.
-
创建CLLocationManager类的实例,并在应用程序的某个位置存储对它的强引用。
Keeping a strong reference to the location manager object is required until all tasks involving that object are complete. Because most location manager tasks run asynchronously, storing your location manager in a local variable is insufficient.
在涉及该对象的所有任务完成之前,需要保留对位置管理器对象的强引用。 由于大多数位置管理器任务以异步方式运行,因此将位置管理器存储在本地变量中是不够的。
- Assign a custom object to the
delegate
property. This object must conform to theCLLocationManagerDelegate
protocol.
- 将自定义对象分配给delegate属性。 该对象必须符合CLLocationManagerDelegate协议。
- Configure the properties related to the service you intend to use. For example, when getting location updates, always configure the
distanceFilter
anddesiredAccuracy
properties.
- 配置与您要使用的服务相关的属性。 例如,获取位置更新时,请始终配置distanceFilter和desiredAccuracyproperties。
- Call the appropriate method to start the delivery of events.
- 调用适当的方法开始传递事件。
For the services you use, configure any properties associated with that service accurately. Core Location manages power aggressively by turning off hardware when it is not needed. For example, setting the desired accuracy for location events to one kilometer gives the location manager the flexibility to turn off GPS hardware and rely solely on the WiFi or cell radios, which can lead to significant power savings.
- 对于您使用的服务,请准确配置与该服务关联的所有属性。 核心位置通过在不需要时关闭硬件来积极地管理电源。 例如,将位置事件的所需精度设置为一公里,使位置管理员能够灵活地关闭GPS硬件并仅依靠WiFi或蜂窝无线电,这可以显着节省功率。
All location- and heading-related updates are delivered to the associated delegate object, which is a custom object that you provide. For information about the delegate methods you use to receive events, see CLLocationManagerDelegate
.
- 所有与位置和标题相关的更新都将传递到关联的委托对象,该对象是您提供的自定义对象。 有关用于接收事件的委托方法的信息,请参阅CLLocationManagerDelegate。
CLLocationManagerDelegate
The methods that you use to receive events from an associated location manager object.
- 用于从关联的位置管理器对象接收事件的方法。
Overview
The location manager calls the methods of this delegate to report location-related events to your app. Implement this protocol in an app-specific object and use the methods to update your app. For example, you might use the current location to update the user's position on a map or you might return search results relevant only to the user's current location.
- 位置管理员调用此委托的方法向您的应用报告与位置相关的事件。 在特定于应用程序的对象中实现此协议,并使用这些方法更新您的应用程序。 例如,您可以使用当前位置更新用户在地图上的位置,或者您可能返回仅与用户当前位置相关的搜索结果。
Important
Always implement the methods for handling any potential failures in addition to the methods for receiving location-related data.
- 除了接收与位置相关的数据的方法之外,始终实施处理任何潜在故障的方法。
Assign your delegate object to the delegate
property of the CLLocationManager
object before starting any services. Core Location may report a cached value to your delegate immediately after you start the service, followed by a more current value later. Check the time stamp of any data objects you receive before using them.
- 在启动任何服务之前,将委托对象分配给CLLocationManager对象的委托属性。 启动服务后,Core Location可能会立即向您的代理报告缓存值,之后会显示更新的值。 在使用之前检查您收到的任何数据对象的时间戳。
The methods of your delegate object are called from the thread in which you started the corresponding location services. That thread must itself have an active run loop, like the one found in your application’s main thread.
- 委托对象的方法是从启动相应位置服务的线程中调用的。 该线程本身必须有一个活动的运行循环,就像在应用程序的主线程中找到的那样。
Determining the Availability of Location Services
Determine which location services are active and available on the user's device.
- 确定用户设备上哪些位置服务处于活动状态且可用。
Overview
Not all Core Location services are available on every device, and services may be temporarily unavailable in certain circumstances:
并非所有Core Location服务都可在每台设备上使用,并且在某些情况下服务可能暂时不可用:
-
The device does not have the hardware needed to support the feature.
- 设备没有支持该功能所需的硬件。
-
The user disabled location services in the system settings.
- 用户在系统设置中禁用了位置服务。
-
The user denied access to location services for your app.
- 用户拒绝访问您的应用的位置服务。
-
The user's device is in Airplane Mode and unable to gather location data.
- 用户的设备处于飞行模式,无法收集位置数据。
-
Background App Refresh is disabled and you are monitoring regions or using the significant-change location service, which requires that feature.
- 后台应用程序刷新已禁用,您正在监视区域或使用重要更改位置服务,这需要该功能。
Before using any specific location service, check the availability of that service using the methods of your CLLocationManager
object. Table 1 lists the methods you call and explains any hardware requirements for the corresponding services.
- 在使用任何特定位置服务之前,请使用CLLocationManager对象的方法检查该服务的可用性。 表1列出了您调用的方法,并解释了相应服务的所有硬件要求。
Table 1 Getting the availability of Core Location services
- 表1获取核心位置服务的可用性
-
locationEnabled()
,Tells whether you can get the geographic coordinate for the user's current location. This service is generally available on all devices. See Getting the User's Location.- 告诉您是否可以获取用户当前位置的地理坐标。 此服务通常适用于所有设备。 请参阅获取用户的位置。
significantLocationChangeMonitoringAvailable()
,Tells whether you can get the user's location using the signficant-change location service. This service requires specific hardware and may not be available on all devices. See Getting the User's Location.
- 告诉您是否可以使用signficant-change位置服务获取用户的位置。 此服务需要特定硬件,可能并非在所有设备上都可用。 请参阅获取用户的位置。
-
MonitoringAvailable(for:)
,Tells whether you can use region monitoring to detect entry into or exit from geographic regions or iBeacon regions. Support for geographic region monitoring requires specific hardware and is generally available on all iOS devices. Support for iBeacon region monitoring requires Bluetooth hardware and is generally available on all devices. For information on how to monitor geographic regions, see Monitoring the User's Proximity to Geographic Regions. For information on how to monitor iBeacon regions, see Determining the Proximity to an iBeacon.
- 告诉您是否可以使用区域监控来检测进入或退出地理区域或iBeacon区域。 对地理区域监控的支持需要特定的硬件,并且通常可在所有iOS设备上使用。 支持iBeacon区域监控需要蓝牙硬件,并且通常可在所有设备上使用。 有关如何监视地理区域的信息,请参阅监视用户与地理区域的接近度。 有关如何监视iBeacon区域的信息,请参阅确定与iBeacon的接近度。
-
headingAvailable()
,Tells whether the device is able to provide compass-related headings. This service requires the presence of a magnetometer. See Getting Heading and Course Information.
- 告知设备是否能够提供与罗盘相关的标题。 该服务需要磁力计的存在。 请参阅获取标题和课程信息。
-
isRangingAvailable()
,Tells whether you can obtain the relative distance to a nearby iBeacon. This service requires Bluetooth hardware and is generally available on all devices. See Determining the Proximity to an iBeacon.
- 告诉您是否可以获得与附近iBeacon的相对距离。 此服务需要蓝牙硬件,并且通常可在所有设备上使用。 请参阅确定与iBeacon的接近度。
Listing 1 shows how to check for the availability of the standard location service. Based on the availability of those services, you would enable or disable features of your app accordingly.
- 清单1显示了如何检查标准位置服务的可用性。 根据这些服务的可用性,您可以相应地启用或禁用应用程序的功能。
Listing 1 Checking for the availability of the standard location service
- 清单1检查标准位置服务的可用性
func checkForLocationServices() {
if CLLocationManager.locationServicesEnabled() {
// Location services are available, so query the user’s location.
} else {
// Update your app’s UI to show that the location is unavailable.
}
}
If you try to start a service that is unavailable, the CLLocationManager
object calls one of the failure-related methods of its delegate. For example, if region monitoring is unavailable, it calls the locationManager(_:monitoringDidFailFor:withError:)
method.
- 如果尝试启动不可用的服务,则CLLocationManager对象将调用其委托的其中一个与故障相关的方法。 例如,如果区域监视不可用,则调用locationManager(_:monitoringDidFailFor:withError :)方法。
Note
Apps should fail gracefully and offer other useful capabilities when services are not available. If the absence of a service renders your app useless, you can indicate the requirement of that service in your app'sInfo.plist
. For more information, see Requiring the Presence of Specific Location Services.
- 注意:应用程序应正常失败,并在服务不可用时提供其他有用的功能。 如果缺少某项服务会导致您的应用无效,您可以在应用的Info.plist中指明该服务的要求。 有关更多信息,请参阅要求存在特定位置服务。
Requiring the Presence of Specific Location Services
Declare the location services that your app requires.
- 声明您的应用所需的位置服务。
Overview
If your app requires the presence of specific location-related hardware, you must declare those requirements in the app’s Info.plist file. For new iOS projects, Xcode includes the Required device capabilities key in the Info.plist file. The value of this key is an array of strings, each of which specifies a type of hardware that must be present on the device. The App Store prevents the installation of apps on devices that do not support the required hardware. You can add the following strings to indicate that you require the specified hardware or services:
- 如果您的应用需要存在特定的与位置相关的硬件,则必须在应用的Info.plist文件中声明这些要求。 对于新的iOS项目,Xcode包含Info.plist文件中的Required device capabilities键。 此键的值是一个字符串数组,每个字符串都指定必须存在于设备上的硬件类型。 App Store会阻止在不支持所需硬件的设备上安装应用程序。 您可以添加以下字符串以指示您需要指定的硬件或服务:
Table 1 Keys for requiring location services
- 表1要求定位服务的关键
-
key
: location-services,description
: Include this key if your app requires location services. Always include it if you also include the gps or magnetometer key.
- 如果您的应用需要位置服务,请添加这个键。 如果您还包括gps或磁力计键,请务必包含它。
-
key
: gps,description
: Include this key if your app requires GPS-level precision for locations, or if you require course information. Navigation apps typically include this key in their Info.plist.
- 如果您的应用需要GPS级别的精确位置,或者您需要课程信息,请包含此密钥。 导航应用程序通常在其Info.plist中包含此密钥。
-
key
: magnetometer,description
: Include this key if your app uses heading information, which requires the presence of a magnetometer.
- 如果您的应用使用标题信息,则需要包含此键,这需要磁力计的存在。
If your app is able to function without the specified capabilities, do not include them as requirements.
- 如果您的应用程序能够在没有指定功能的情况下运行,请不要将它们包含在要求中。
Choosing the Authorization Level for Location Services
Choose the appropriate level of access to location data for your app.
- 为您的应用选择适当的位置数据访问级别。
Overview
The type of authorization (“when-in-use” or “always”) that you request determines which location services your app can access and when it can use them:
- 您请求的授权类型(“使用中”或“始终”)确定您的应用可以访问哪些位置服务以及何时可以使用它们:
- When-in-use authorization. Your app can use most services but cannot use services that automatically relaunch the app. Your app must always start services while running in the foreground. If you enable the background location capability for your app, a suspended app will wake in the background to handle location events. However, if your app is not running, it will not be launched.
- 您的应用可以使用大多数服务,但无法使用自动重新启动应用的服务。 您的应用必须始终在前台运行时启动服务。 如果您为应用启用了后台定位功能,则会在后台唤醒已暂停的应用以处理位置事件。 但是,如果您的应用未运行,则无法启动。
-
Always authorization. Your app can use all location services, and it can start those services from either the foreground or the background. If a location-related event occurs when your app is not running, the system launches your app and delivers the event.
It is recommended that you request only when-in-use authorization whenever possible. If your app requests and receives when-in-use authorization, you can make a separate request for always authorization later. (Apps may make only one request for always authorization.) Even if you request always authorization, the user has the option of granting your app when-in-use authorization instead. So you must always be prepared to run with when-in-use authorization.
- 您的应用可以使用所有位置服务,它可以从前台或后台启动这些服务。 如果您的应用未运行时发生与位置相关的事件,系统会启动您的应用并发送活动。
建议您尽可能只请求使用中的授权。 如果您的应用程序请求并接收使用中授权,您可以在以后单独请求始终授权。 (应用程序可能只会发出一次始终授权请求。)即使您始终请求授权,用户也可以选择授予您的应用程序使用时授权。 因此,您必须始终准备好与使用中授权一起运行。
It is recommended that you request only when-in-use authorization whenever possible. If your app requests and receives when-in-use authorization, you can make a separate request for always authorization later. (Apps may make only one request for always authorization.) Even if you request always authorization, the user has the option of granting your app when-in-use authorization instead. So you must always be prepared to run with when-in-use authorization.
- 建议您尽可能只请求使用中的授权。 如果您的应用程序请求并接收使用中授权,您可以在以后单独请求始终授权。 (应用程序可能只会发出一次始终授权请求。)即使您始终请求授权,用户也可以选择授予您的应用程序使用时授权。 因此,您必须始终准备好与使用中授权一起运行。
Important
Always request authorization at the point where you the user needs location services to perform a task, such as when the user activates a feature that requires the current location. Requesting authorization may display an alert to the user. If it's not clear to the user why your app is using location services, the user may deny your request.
- 始终在用户需要位置服务的位置请求授权以执行任务,例如当用户激活需要当前位置的功能时。 请求授权可以向用户显示警报。 如果用户不清楚您的应用为何使用位置服务,则用户可能会拒绝您的请求。
Table 1 lists the location services available for each type of authorization.
- 表1列出了每种授权可用的位置服务。
Table 1 Authorizations supported by the location services
- 表1位置服务支持的授权
After making an authorization request, it is safe to start location services before your request is resolved. However, location services do not deliver any data until the authorization status changes to CLAuthorizationStatus.authorizedAlways
or CLAuthorizationStatus.authorizedWhenInUse
. Implement the locationManager(_:didChangeAuthorization:)
method in your location manager delegate to be notified when your app's authorization status changes.
- 发出授权请求后,在您的请求得到解决之前启动位置服务是安全的。 但是,在授权状态更改为CLAuthorizationStatus.authorizedAlways或CLAuthorizationStatus.authorizedWhenInUse之前,位置服务不会传递任何数据。 在您的位置管理器委托中实施locationManager(_:didChangeAuthorization :)方法,以便在您的应用程序的授权状态发生变化时收到通知。
releated:
Requesting When-In-Use Authorization
https://developer.apple.com/documentation/corelocation/choosing_the_authorization_level_for_location_services/requesting_when-in-use_authorization
Requesting Always Authorization https://developer.apple.com/documentation/corelocation/choosing_the_authorization_level_for_location_services/requesting_always_authorization
Requesting When-In-Use Authorization
Request authorization to use location services only when your app is running.
- 仅在您的应用运行时请求授权才能使用位置服务。
Overview
To configure when-in-use authorization for location services, follow these steps (Listing 1demonstrates steps 2 and 3.):
- 要配置位置服务的使用时授权,请按照下列步骤操作(清单1演示步骤2和3):
- Add the
NSLocationWhenInUseUsageDescription
key to your app'sInfo.plist
file. (Xcode displays this key as "Privacy - Location When In Use Usage Description" in the Info.plist editor.)
- 将NSLocationWhenInUseUsageDescription键添加到应用程序的Info.plist文件中。 (Xcode在Info.plist编辑器中将此密钥显示为“隐私 - 使用时的位置使用说明”。)
- Create and configure your
CLLocationManager
object.
- 创建和配置CLLocationManager对象。
- Call the
requestWhenInUseAuthorization()
method of yourCLLocationManager
object prior to starting any location services.
- 在启动任何位置服务之前,调用CLLocationManagerobject的requestWhenInUseAuthorization()方法。
Important
You must add the NSLocationWhenInUseUsageDescription key to your app's Info.plist file. If that key is not present, authorization requests fail immediately.
- 您必须将NSLocationWhenInUseUsageDescription键添加到应用程序的Info.plist文件中。 如果该密钥不存在,则授权请求立即失败。
Request authorization at the point where you need location services. For example, wait until the user activates a feature of your app that requires location data. Don't request authorization at launch time unless you need the user's location immediately or your app was launched in the background by the system to handle a location update.
- 在您需要位置服务的位置请求授权。 例如,等到用户激活需要位置数据的应用功能。 除非您立即需要用户的位置或者您的应用程序是由系统在后台启动以处理位置更新,否则请勿在启动时请求授权。
Request When-In-Use Authorization
Listing 1 shows how you might request when-in-use authorization before starting your app's location-related services, by calling the requestWhenInUseAuthorization()
method. You need to request authorization only when your app's authorization status is not determined. If your app's authorization status is already determined, you can simply start the services that you need.
- 清单1显示了如何通过调用requestWhenInUseAuthorization()方法在启动应用程序的位置相关服务之前请求使用中授权。 只有在未确定应用程序的授权状态时,您才需要请求授权。 如果您的应用程序的授权状态已经确定,您只需启动所需的服务即可。
Listing 1 Requesting authorization to use location services
let locationManager = CLLocationManager()
func enableBasicLocationServices() {
locationManager.delegate = self
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
// Request when-in-use authorization initially
locationManager.requestWhenInUseAuthorization()
break
case .restricted, .denied:
// Disable location features
disableMyLocationBasedFeatures()
break
case .authorizedWhenInUse, .authorizedAlways:
// Enable location features
enableMyWhenInUseFeatures()
break
}
}
}
Respond to Changes in Authorization Status
When you make an authorization request, Core Location processes your request asynchronously and delivers the results to the locationManager(_:didChangeAuthorization:)
method of your location manager's delegate object. Use that method to determine whether the user granted or denied your request, and to take any appropriate actions in response.
- 当您发出授权请求时,Core Location会异步处理您的请求,并将结果传递给您的位置管理器委托对象的locationManager(_:didChangeAuthorization :)方法。 使用该方法确定用户是授予还是拒绝您的请求,并采取任何适当的操作作为响应。
Listing 2 shows an implementation of the locationManager(_:didChangeAuthorization:)
method that enables the app's location-related features when the app receives authorization and disables those features when authorization is denied or restricted for any reason.
- 显示了locationManager(_:didChangeAuthorization :)方法的实现,该方法在应用程序接收授权时启用应用程序的位置相关功能,并在授权被拒绝或因任何原因受到限制时禁用这些功能。
Listing 2 Getting changes to the app's authorization
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted, .denied:
disableMyLocationBasedFeatures()
break
case .authorizedWhenInUse:
enableMyWhenInUseFeatures()
break
case .notDetermined, .authorizedAlways:
break
}
}
Important
The availability of location services may change at any time. The user can disable location services in the system settings, either for your app specifically or for all apps. Location services are also disabled when a device enters Airplane mode, and they may resume when the device leaves Airplane mode. If your app is running (either in the foreground or in the background) when the availability status changes, the system calls yourlocationManager(_:didChangeAuthorization:)
method to notify you of the change.
- 位置服务的可用性可能随时发生变化。 用户可以在系统设置中禁用位置服务,无论是专门针对您的应用还是针对所有应用。 当设备进入飞行模式时,位置服务也会被禁用,当设备离开飞行模式时,它们可能会恢复。 如果您的应用程序在可用性状态更改时正在运行(在前台或后台),系统会调用您的locationManager(_:didChangeAuthorization :)方法来通知您更改。
Requesting Always Authorization
Request authorization to use location services at any time.
- 请求授权随时使用位置服务。
Overview
To configure always authorization for location services, follow these steps (Listing 1demonstrates steps 3-5):
要始终配置位置服务的授权,请按照下列步骤操作(清单1演示步骤3-5):
- Add the
NSLocationWhenInUseUsageDescription
key and theNSLocationAlwaysAndWhenInUseUsageDescription
key to yourInfo.plist
file. (Xcode displays these keys as "Privacy - Location When In Use Usage Description" and "Privacy - Location Always and When In Use Usage Description" in theInfo.plist
editor.)
- 将NSLocationWhenInUseUsageDescription键和NSLocationAlwaysAndWhenInUseUsageDescription键添加到Info.plist文件中。 (Xcode在Info.plist编辑器中将这些密钥显示为“隐私 - 使用时的位置使用说明”和“隐私 - 始终和使用时的位置使用说明”。)
- If your app supports iOS 10 and earlier, add the
NSLocationAlwaysUsageDescription
key to yourInfo.plist
file. (Xcode displays this key as "Privacy - Location Always Usage Description" in theInfo.plist
editor.)
- 如果您的应用支持iOS 10及更早版本,请将NSLocationAlwaysUsageDescription键添加到Info.plist文件中。 (Xcode在Info.plist编辑器中将此密钥显示为“Privacy - Location Always Usage Description”。)
- Create and configure your
CLLocationManager
object.
- 创建和配置CLLocationManager对象。
- Call the
requestWhenInUseAuthorization()
initially to enable your app's basic location support.
- 最初调用requestWhenInUseAuthorization()以启用应用程序的基本位置支持。
- Call the
requestAlwaysAuthorization()
method only when the user enables a feature of your app that requires that level of authorization.
- 仅当用户启用需要该级别授权的应用程序功能时,才调用requestAlwaysAuthorization()方法。
Don't request authorization at launch time unless you need the user's location immediately or were launched in the background to receive a location update.
- 除非您立即需要用户的位置或在后台启动以接收位置更新,否则请勿在启动时请求授权。
Important
You are required to include the NSLocationWhenInUseUsageDescription and NSLocationAlwaysAndWhenInUseUsageDescription keys in your app's Info.plist file. (If your app supports iOS 10 and earlier, the NSLocationAlwaysUsageDescription key is also required.) If those keys are not present, authorization requests fail immediately.
- 您需要在应用程序的Info.plist文件中包含NSLocationWhenInUseUsageDescription和NSLocationAlwaysAndWhenInUseUsageDescription键。 (如果您的应用支持iOS 10及更早版本,则还需要NSLocationAlwaysUsageDescription键。)如果这些键不存在,则授权请求会立即失败。
Enable When-In-Use Authorization Before Always Authorization
Listing 1 shows one way to enable your app's location services initially. If your app's authorization status is already determined, you don't need to request authorizationa gain. If your app's authorization status is not determined, try to limit your initial authorization request to when-in-use authorization. You can request always authorization right away if your app requires the corresponding location services, but be prepared for the user to grant only when-in-use authorization or to deny your request altogether.
- 清单1显示了一种最初启用应用程序位置服务的方法。 如果您的应用程序的授权状态已经确定,则无需申请授权。 如果您的应用程序的授权状态未确定,请尝试将初始授权请求限制为使用中授权。 如果您的应用需要相应的位置服务,您可以立即请求授权,但要准备好让用户仅授予使用中授权或完全拒绝您的请求。
Listing 1 Requesting authorization to use location services
let locationManager = CLLocationManager()
func enableLocationServices() {
locationManager.delegate = self
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
// Request when-in-use authorization initially
locationManager.requestWhenInUseAuthorization()
break
case .restricted, .denied:
// Disable location features
disableMyLocationBasedFeatures()
break
case .authorizedWhenInUse:
// Enable basic location features
enableMyWhenInUseFeatures()
break
case .authorizedAlways:
// Enable any of your app's location features
enableMyAlwaysFeatures()
break
}
}
}
Escalate the App's Authorization Level
In iOS 11 and later, if you initially requested only when-in-use authorization, you can call the requestAlwaysAuthorization()
method at a later time (as shown in Listing 2) to escalate your app's authorization level. When requesting always authorization, the system displays the usage description string stored in the NSLocationAlwaysAndWhenInUseUsageDescription
key of your Info.plist
file. The user must then choose whether to grant the request for always authorization or to leave your app with when-in-use authorization. The system lets your app escalate its authorization level only once, displaying an appropriate interface to the user when you do. Subsequent attempts do not display a system interface and do not change your app's authorization level.
- 在iOS 11及更高版本中,如果您最初仅请求使用中授权,则可以稍后调用requestAlwaysAuthorization()方法(如清单2所示)以升级应用程序的授权级别。 请求始终授权时,系统将显示存储在Info.plist文件的NSLocationAlwaysAndWhenInUseUsageDescription键中的使用情况说明字符串。 然后,用户必须选择是否授予始终授权的请求,或者让您的应用程序使用何时授权。 系统允许您的应用仅升级其授权级别一次,在您执行时向用户显示适当的界面。 后续尝试不显示系统界面,也不会更改应用程序的授权级别。
Listing 2 Escalating from when-in-use to always authorization
func escalateLocationServiceAuthorization() {
// Escalate only when the authorization is set to when-in-use
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
locationManager.requestAlwaysAuthorization()
}
}
Respond to Changes in Authorization Status
When you request authorization, or when your app's authorization status changes, use the locationManager(_:didChangeAuthorization:)
method of your delegate object to process the changes. Listing 3 shows an implementation of that method that enables or disables features based on the app's current authorization level.
- 当您请求授权或应用程序的授权状态发生更改时,请使用委托对象的locationManager(_:didChangeAuthorization :)方法来处理更改。 清单3显示了该方法的实现,该方法根据应用程序的当前授权级别启用或禁用功能。
Listing 3 Getting changes to the app's authorization
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) { switch status {
case .restricted, .denied:
// Disable your app's location features
disableMyLocationBasedFeatures()
break
case .authorizedWhenInUse:
// Enable only your app's when-in-use features.
enableMyWhenInUseFeatures()
break
case .authorizedAlways:
// Enable any of your app's location services.
enableMyAlwaysFeatures()
break
case .notDetermined:
break
}
}
Important
The availability of location services may change at any time. The user can disable location services in the system settings, either for your app specifically or for all apps. Location services are also disabled when a device enters Airplane mode, and they may resume when the device leaves Airplane mode. If your app is running (either in the foreground or in the background) when the availability status changes, the system calls your
locationManager(_:didChangeAuthorization:)
method to notify you of the change.
- 位置服务的可用性可能随时发生变化。 用户可以在系统设置中禁用位置服务,无论是专门针对您的应用还是针对所有应用。 当设备进入飞行模式时,位置服务也会被禁用,当设备离开飞行模式时,它们可能会恢复。 如果您的应用程序在可用性状态更改时正在运行(在前台或后台),系统会调用您的locationManager(_:didChangeAuthorization :)方法来通知您更改。