CLLocationManager

The object that you use to start and stop the delivery of location-related events to your app.

  • 用于啟動(dòng)和停止向應(yīng)用程序傳遞與位置相關(guān)的事件的對(duì)象。

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:

  • 您可以使用此類(lèi)的實(shí)例來(lái)配置钧萍,啟動(dòng)和停止Core Location服務(wù)。 位置管理器對(duì)象支持以下與位置相關(guān)的活動(dòng):

Tracking large or small changes in the user’s current location with a configurable degree of accuracy.

  • 使用可配置的準(zhǔn)確度跟蹤用戶(hù)當(dāng)前位置的大小變化。

Reporting heading changes from the onboard compass. (iOS only)

  • 從機(jī)載羅盤(pán)報(bào)告航向變化。 (僅限iOS)

Monitoring distinct regions of interest and generating location events when the user enters or leaves those regions.

  • 監(jiān)控不同的感興趣區(qū)域并在用戶(hù)進(jìn)入或離開(kāi)這些區(qū)域時(shí)生成位置事件通熄。

Deferring the delivery of location updates while the app is in the background. (iOS only)

  • 在應(yīng)用程序處于后臺(tái)時(shí)推遲傳遞位置更新决采。 (僅限iOS)

Reporting the range to nearby beacons.

  • 將范圍報(bào)告給附近的信標(biāo)。

When you are ready to use location services, follow these steps:

  • 準(zhǔn)備好使用位置服務(wù)時(shí)纵柿,請(qǐng)按照下列步驟操作:
  1. 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.
  • 檢查您的應(yīng)用是否有權(quán)使用位置服務(wù),并在尚未確定您的應(yīng)用的授權(quán)狀態(tài)時(shí)請(qǐng)求許可启绰,如請(qǐng)求使用位置服務(wù)的權(quán)限中所述藐窄。
  1. Check to see if the appropriate location services are available for you to use, as described in Determining the Availability of Location Services.
    檢查是否有適合您使用的位置服務(wù),如確定位置服務(wù)的可用性中所述酬土。

  2. Create an instance of the CLLocationManager class and store a strong reference to it somewhere in your app.

  • 創(chuàng)建CLLocationManager類(lèi)的實(shí)例荆忍,并在應(yīng)用程序的某個(gè)位置存儲(chǔ)對(duì)它的強(qiáng)引用。

    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.

  • 在涉及該對(duì)象的所有任務(wù)完成之前撤缴,需要保留對(duì)位置管理器對(duì)象的強(qiáng)引用刹枉。 由于大多數(shù)位置管理器任務(wù)以異步方式運(yùn)行,因此將位置管理器存儲(chǔ)在本地變量中是不夠的屈呕。

  1. Assign a custom object to the delegate property. This object must conform to the CLLocationManagerDelegate protocol.
  • 將自定義對(duì)象分配給delegate屬性微宝。 該對(duì)象必須符合CLLocationManagerDelegate協(xié)議。
  1. Configure the properties related to the service you intend to use. For example, when getting location updates, always configure the distanceFilter and desiredAccuracyproperties.
  • 配置與您要使用的服務(wù)相關(guān)的屬性虎眨。 例如蟋软,獲取位置更新時(shí),請(qǐng)始終配置distanceFilter和desiredAccuracyproperties嗽桩。
  1. Call the appropriate method to start the delivery of events.
  • 調(diào)用適當(dāng)?shù)姆椒ㄩ_(kāi)始傳遞事件岳守。

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.

  • 對(duì)于您使用的服務(wù),請(qǐng)準(zhǔn)確配置與該服務(wù)關(guān)聯(lián)的所有屬性碌冶。 核心位置通過(guò)在不需要時(shí)關(guān)閉硬件來(lái)積極地管理電源湿痢。 例如,將位置事件的所需精度設(shè)置為一公里扑庞,使位置管理員能夠靈活地關(guān)閉GPS硬件并僅依靠WiFi或蜂窩無(wú)線(xiàn)電譬重,這可以顯著節(jié)省功率。

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.

  • 所有與位置和標(biāo)題相關(guān)的更新都將傳遞到關(guān)聯(lián)的委托對(duì)象罐氨,該對(duì)象是您提供的自定義對(duì)象臀规。 有關(guān)用于接收事件的委托方法的信息,請(qǐng)參閱CLLocationManagerDelegate栅隐。

CLLocationManagerDelegate

The methods that you use to receive events from an associated location manager object.

  • 用于從關(guān)聯(lián)的位置管理器對(duì)象接收事件的方法塔嬉。

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.

  • 位置管理員調(diào)用此委托的方法向您的應(yīng)用報(bào)告與位置相關(guān)的事件狠怨。 在特定于應(yīng)用程序的對(duì)象中實(shí)現(xiàn)此協(xié)議,并使用這些方法更新您的應(yīng)用程序邑遏。 例如,您可以使用當(dāng)前位置更新用戶(hù)在地圖上的位置恰矩,或者您可能返回僅與用戶(hù)當(dāng)前位置相關(guān)的搜索結(jié)果记盒。

Important

Always implement the methods for handling any potential failures in addition to the methods for receiving location-related data.

  • 除了接收與位置相關(guān)的數(shù)據(jù)的方法之外,始終實(shí)施處理任何潛在故障的方法外傅。

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.

  • 在啟動(dòng)任何服務(wù)之前纪吮,將委托對(duì)象分配給CLLocationManager對(duì)象的委托屬性。 啟動(dòng)服務(wù)后萎胰,Core Location可能會(huì)立即向您的代理報(bào)告緩存值碾盟,之后會(huì)顯示更新的值。 在使用之前檢查您收到的任何數(shù)據(jù)對(duì)象的時(shí)間戳技竟。

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.

  • 委托對(duì)象的方法是從啟動(dòng)相應(yīng)位置服務(wù)的線(xiàn)程中調(diào)用的冰肴。 該線(xiàn)程本身必須有一個(gè)活動(dòng)的運(yùn)行循環(huán),就像在應(yīng)用程序的主線(xiàn)程中找到的那樣榔组。

Determining the Availability of Location Services

Determine which location services are active and available on the user's device.

  • 確定用戶(hù)設(shè)備上哪些位置服務(wù)處于活動(dòng)狀態(tài)且可用熙尉。

Overview

Not all Core Location services are available on every device, and services may be temporarily unavailable in certain circumstances:
并非所有Core Location服務(wù)都可在每臺(tái)設(shè)備上使用,并且在某些情況下服務(wù)可能暫時(shí)不可用:

  • The device does not have the hardware needed to support the feature.

    • 設(shè)備沒(méi)有支持該功能所需的硬件搓扯。
  • The user disabled location services in the system settings.

    • 用戶(hù)在系統(tǒng)設(shè)置中禁用了位置服務(wù)检痰。
  • The user denied access to location services for your app.

    • 用戶(hù)拒絕訪(fǎng)問(wèn)您的應(yīng)用的位置服務(wù)。
  • The user's device is in Airplane Mode and unable to gather location data.

    • 用戶(hù)的設(shè)備處于飛行模式锨推,無(wú)法收集位置數(shù)據(jù)铅歼。
  • Background App Refresh is disabled and you are monitoring regions or using the significant-change location service, which requires that feature.

    • 后臺(tái)應(yīng)用程序刷新已禁用,您正在監(jiān)視區(qū)域或使用重要更改位置服務(wù)换可,這需要該功能椎椰。

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.

  • 在使用任何特定位置服務(wù)之前,請(qǐng)使用CLLocationManager對(duì)象的方法檢查該服務(wù)的可用性沾鳄。 表1列出了您調(diào)用的方法俭识,并解釋了相應(yīng)服務(wù)的所有硬件要求。

Table 1 Getting the availability of Core Location services

  • 表1獲取核心位置服務(wù)的可用性
  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.

    • 告訴您是否可以獲取用戶(hù)當(dāng)前位置的地理坐標(biāo)套媚。 此服務(wù)通常適用于所有設(shè)備。 請(qǐng)參閱獲取用戶(hù)的位置磁椒。
  2. 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位置服務(wù)獲取用戶(hù)的位置。 此服務(wù)需要特定硬件浆熔,可能并非在所有設(shè)備上都可用本辐。 請(qǐng)參閱獲取用戶(hù)的位置。
  1. 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.
  • 告訴您是否可以使用區(qū)域監(jiān)控來(lái)檢測(cè)進(jìn)入或退出地理區(qū)域或iBeacon區(qū)域慎皱。 對(duì)地理區(qū)域監(jiān)控的支持需要特定的硬件老虫,并且通常可在所有iOS設(shè)備上使用茫多。 支持iBeacon區(qū)域監(jiān)控需要藍(lán)牙硬件祈匙,并且通常可在所有設(shè)備上使用天揖。 有關(guān)如何監(jiān)視地理區(qū)域的信息夺欲,請(qǐng)參閱監(jiān)視用戶(hù)與地理區(qū)域的接近度。 有關(guān)如何監(jiān)視iBeacon區(qū)域的信息今膊,請(qǐng)參閱確定與iBeacon的接近度些阅。
  1. 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.
  • 告知設(shè)備是否能夠提供與羅盤(pán)相關(guān)的標(biāo)題斑唬。 該服務(wù)需要磁力計(jì)的存在市埋。 請(qǐng)參閱獲取標(biāo)題和課程信息。
  1. 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的相對(duì)距離腰素。 此服務(wù)需要藍(lán)牙硬件,并且通逞┯可在所有設(shè)備上使用弓千。 請(qǐng)參閱確定與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顯示了如何檢查標(biāo)準(zhǔn)位置服務(wù)的可用性献起。 根據(jù)這些服務(wù)的可用性洋访,您可以相應(yīng)地啟用或禁用應(yīng)用程序的功能。

Listing 1 Checking for the availability of the standard location service

  • 清單1檢查標(biāo)準(zhǔn)位置服務(wù)的可用性
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.

  • 如果嘗試啟動(dòng)不可用的服務(wù)谴餐,則CLLocationManager對(duì)象將調(diào)用其委托的其中一個(gè)與故障相關(guān)的方法姻政。 例如,如果區(qū)域監(jiān)視不可用岂嗓,則調(diào)用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's Info.plist. For more information, see Requiring the Presence of Specific Location Services.

  • 注意:應(yīng)用程序應(yīng)正常失敗,并在服務(wù)不可用時(shí)提供其他有用的功能厌殉。 如果缺少某項(xiàng)服務(wù)會(huì)導(dǎo)致您的應(yīng)用無(wú)效食绿,您可以在應(yīng)用的Info.plist中指明該服務(wù)的要求。 有關(guān)更多信息公罕,請(qǐng)參閱要求存在特定位置服務(wù)器紧。

Requiring the Presence of Specific Location Services

Declare the location services that your app requires.

  • 聲明您的應(yīng)用所需的位置服務(wù)。

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:

  • 如果您的應(yīng)用需要存在特定的與位置相關(guān)的硬件楼眷,則必須在應(yīng)用的Info.plist文件中聲明這些要求铲汪。 對(duì)于新的iOS項(xiàng)目熊尉,Xcode包含Info.plist文件中的Required device capabilities鍵。 此鍵的值是一個(gè)字符串?dāng)?shù)組掌腰,每個(gè)字符串都指定必須存在于設(shè)備上的硬件類(lèi)型狰住。 App Store會(huì)阻止在不支持所需硬件的設(shè)備上安裝應(yīng)用程序。 您可以添加以下字符串以指示您需要指定的硬件或服務(wù):

Table 1 Keys for requiring location services

  • 表1要求定位服務(wù)的關(guān)鍵
  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.
  • 如果您的應(yīng)用需要位置服務(wù)齿梁,請(qǐng)?zhí)砑舆@個(gè)鍵催植。 如果您還包括gps或磁力計(jì)鍵,請(qǐng)務(wù)必包含它士飒。
  1. 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.
  • 如果您的應(yīng)用需要GPS級(jí)別的精確位置,或者您需要課程信息蔗崎,請(qǐng)包含此密鑰酵幕。 導(dǎo)航應(yīng)用程序通常在其Info.plist中包含此密鑰。
  1. key: magnetometer, description: Include this key if your app uses heading information, which requires the presence of a magnetometer.
  • 如果您的應(yīng)用使用標(biāo)題信息缓苛,則需要包含此鍵芳撒,這需要磁力計(jì)的存在。

If your app is able to function without the specified capabilities, do not include them as requirements.

  • 如果您的應(yīng)用程序能夠在沒(méi)有指定功能的情況下運(yùn)行未桥,請(qǐng)不要將它們包含在要求中笔刹。

Choosing the Authorization Level for Location Services

Choose the appropriate level of access to location data for your app.

  • 為您的應(yīng)用選擇適當(dāng)?shù)奈恢脭?shù)據(jù)訪(fǎng)問(wèn)級(jí)別。

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:

  • 您請(qǐng)求的授權(quán)類(lèi)型(“使用中”或“始終”)確定您的應(yīng)用可以訪(fǎng)問(wèn)哪些位置服務(wù)以及何時(shí)可以使用它們:
  • 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.
  • 您的應(yīng)用可以使用大多數(shù)服務(wù)冬耿,但無(wú)法使用自動(dòng)重新啟動(dòng)應(yīng)用的服務(wù)舌菜。 您的應(yīng)用必須始終在前臺(tái)運(yùn)行時(shí)啟動(dòng)服務(wù)。 如果您為應(yīng)用啟用了后臺(tái)定位功能亦镶,則會(huì)在后臺(tái)喚醒已暫停的應(yīng)用以處理位置事件日月。 但是煤搜,如果您的應(yīng)用未運(yùn)行已烤,則無(wú)法啟動(dòng)。
  • 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.
  • 您的應(yīng)用可以使用所有位置服務(wù)份汗,它可以從前臺(tái)或后臺(tái)啟動(dòng)這些服務(wù)绊起。 如果您的應(yīng)用未運(yùn)行時(shí)發(fā)生與位置相關(guān)的事件精拟,系統(tǒng)會(huì)啟動(dòng)您的應(yīng)用并發(fā)送活動(dòng)。
    建議您盡可能只請(qǐng)求使用中的授權(quán)虱歪。 如果您的應(yīng)用程序請(qǐng)求并接收使用中授權(quán)蜂绎,您可以在以后單獨(dú)請(qǐng)求始終授權(quán)。 (應(yīng)用程序可能只會(huì)發(fā)出一次始終授權(quán)請(qǐng)求笋鄙。)即使您始終請(qǐng)求授權(quán)荡碾,用戶(hù)也可以選擇授予您的應(yīng)用程序使用時(shí)授權(quán)。 因此局装,您必須始終準(zhǔn)備好與使用中授權(quán)一起運(yùn)行坛吁。

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.

  • 建議您盡可能只請(qǐng)求使用中的授權(quán)劳殖。 如果您的應(yīng)用程序請(qǐng)求并接收使用中授權(quán),您可以在以后單獨(dú)請(qǐng)求始終授權(quán)拨脉。 (應(yīng)用程序可能只會(huì)發(fā)出一次始終授權(quán)請(qǐng)求哆姻。)即使您始終請(qǐng)求授權(quán),用戶(hù)也可以選擇授予您的應(yīng)用程序使用時(shí)授權(quán)玫膀。 因此矛缨,您必須始終準(zhǔn)備好與使用中授權(quán)一起運(yùn)行。

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.

  • 始終在用戶(hù)需要位置服務(wù)的位置請(qǐng)求授權(quán)以執(zhí)行任務(wù)帖旨,例如當(dāng)用戶(hù)激活需要當(dāng)前位置的功能時(shí)箕昭。 請(qǐng)求授權(quán)可以向用戶(hù)顯示警報(bào)。 如果用戶(hù)不清楚您的應(yīng)用為何使用位置服務(wù)解阅,則用戶(hù)可能會(huì)拒絕您的請(qǐng)求落竹。

Table 1 lists the location services available for each type of authorization.

  • 表1列出了每種授權(quán)可用的位置服務(wù)。

Table 1 Authorizations supported by the location services

  • 表1位置服務(wù)支持的授權(quán)
image.png

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.

  • 發(fā)出授權(quán)請(qǐng)求后货抄,在您的請(qǐng)求得到解決之前啟動(dòng)位置服務(wù)是安全的述召。 但是,在授權(quán)狀態(tài)更改為CLAuthorizationStatus.authorizedAlways或CLAuthorizationStatus.authorizedWhenInUse之前蟹地,位置服務(wù)不會(huì)傳遞任何數(shù)據(jù)积暖。 在您的位置管理器委托中實(shí)施locationManager(_:didChangeAuthorization :)方法,以便在您的應(yīng)用程序的授權(quán)狀態(tài)發(fā)生變化時(shí)收到通知怪与。

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.

  • 僅在您的應(yīng)用運(yùn)行時(shí)請(qǐng)求授權(quán)才能使用位置服務(wù)夺刑。

Overview

To configure when-in-use authorization for location services, follow these steps (Listing 1demonstrates steps 2 and 3.):

  • 要配置位置服務(wù)的使用時(shí)授權(quán),請(qǐng)按照下列步驟操作(清單1演示步驟2和3):
  1. Add the NSLocationWhenInUseUsageDescription key to your app's Info.plistfile. (Xcode displays this key as "Privacy - Location When In Use Usage Description" in the Info.plist editor.)
  • 將NSLocationWhenInUseUsageDescription鍵添加到應(yīng)用程序的Info.plist文件中分别。 (Xcode在Info.plist編輯器中將此密鑰顯示為“隱私 - 使用時(shí)的位置使用說(shuō)明”性誉。)
  1. Create and configure your CLLocationManager object.
  • 創(chuàng)建和配置CLLocationManager對(duì)象。
  1. Call the requestWhenInUseAuthorization() method of your CLLocationManagerobject prior to starting any location services.
  • 在啟動(dòng)任何位置服務(wù)之前茎杂,調(diào)用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鍵添加到應(yīng)用程序的Info.plist文件中。 如果該密鑰不存在煌往,則授權(quán)請(qǐng)求立即失敗倾哺。

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.

  • 在您需要位置服務(wù)的位置請(qǐng)求授權(quán)。 例如刽脖,等到用戶(hù)激活需要位置數(shù)據(jù)的應(yīng)用功能羞海。 除非您立即需要用戶(hù)的位置或者您的應(yīng)用程序是由系統(tǒng)在后臺(tái)啟動(dòng)以處理位置更新,否則請(qǐng)勿在啟動(dòng)時(shí)請(qǐng)求授權(quán)曲管。

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顯示了如何通過(guò)調(diào)用requestWhenInUseAuthorization()方法在啟動(dòng)應(yīng)用程序的位置相關(guān)服務(wù)之前請(qǐng)求使用中授權(quán)却邓。 只有在未確定應(yīng)用程序的授權(quán)狀態(tài)時(shí),您才需要請(qǐng)求授權(quán)院水。 如果您的應(yīng)用程序的授權(quán)狀態(tài)已經(jīng)確定腊徙,您只需啟動(dòng)所需的服務(wù)即可简十。

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.

  • 當(dāng)您發(fā)出授權(quán)請(qǐng)求時(shí),Core Location會(huì)異步處理您的請(qǐng)求撬腾,并將結(jié)果傳遞給您的位置管理器委托對(duì)象的locationManager(_:didChangeAuthorization :)方法螟蝙。 使用該方法確定用戶(hù)是授予還是拒絕您的請(qǐng)求,并采取任何適當(dāng)?shù)牟僮髯鳛轫憫?yīng)民傻。

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 :)方法的實(shí)現(xiàn)胰默,該方法在應(yīng)用程序接收授權(quán)時(shí)啟用應(yīng)用程序的位置相關(guān)功能,并在授權(quán)被拒絕或因任何原因受到限制時(shí)禁用這些功能漓踢。

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 your locationManager(_:didChangeAuthorization:) method to notify you of the change.

  • 位置服務(wù)的可用性可能隨時(shí)發(fā)生變化牵署。 用戶(hù)可以在系統(tǒng)設(shè)置中禁用位置服務(wù),無(wú)論是專(zhuān)門(mén)針對(duì)您的應(yīng)用還是針對(duì)所有應(yīng)用喧半。 當(dāng)設(shè)備進(jìn)入飛行模式時(shí)奴迅,位置服務(wù)也會(huì)被禁用,當(dāng)設(shè)備離開(kāi)飛行模式時(shí)薯酝,它們可能會(huì)恢復(fù)半沽。 如果您的應(yīng)用程序在可用性狀態(tài)更改時(shí)正在運(yùn)行(在前臺(tái)或后臺(tái))爽柒,系統(tǒng)會(huì)調(diào)用您的locationManager(_:didChangeAuthorization :)方法來(lái)通知您更改吴菠。

Requesting Always Authorization

Request authorization to use location services at any time.

  • 請(qǐng)求授權(quán)隨時(shí)使用位置服務(wù)。

Overview

To configure always authorization for location services, follow these steps (Listing 1demonstrates steps 3-5):
要始終配置位置服務(wù)的授權(quán)浩村,請(qǐng)按照下列步驟操作(清單1演示步驟3-5):

  1. Add the NSLocationWhenInUseUsageDescription key and the NSLocationAlwaysAndWhenInUseUsageDescription key to your Info.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 the Info.plist editor.)
  • 將NSLocationWhenInUseUsageDescription鍵和NSLocationAlwaysAndWhenInUseUsageDescription鍵添加到Info.plist文件中做葵。 (Xcode在Info.plist編輯器中將這些密鑰顯示為“隱私 - 使用時(shí)的位置使用說(shuō)明”和“隱私 - 始終和使用時(shí)的位置使用說(shuō)明”。)
  1. If your app supports iOS 10 and earlier, add the NSLocationAlwaysUsageDescription key to your Info.plist file. (Xcode displays this key as "Privacy - Location Always Usage Description" in the Info.plist editor.)
  • 如果您的應(yīng)用支持iOS 10及更早版本心墅,請(qǐng)將NSLocationAlwaysUsageDescription鍵添加到Info.plist文件中酿矢。 (Xcode在Info.plist編輯器中將此密鑰顯示為“Privacy - Location Always Usage Description”。)
  1. Create and configure your CLLocationManager object.
  • 創(chuàng)建和配置CLLocationManager對(duì)象怎燥。
  1. Call the requestWhenInUseAuthorization() initially to enable your app's basic location support.
  • 最初調(diào)用requestWhenInUseAuthorization()以啟用應(yīng)用程序的基本位置支持瘫筐。
  1. Call the requestAlwaysAuthorization() method only when the user enables a feature of your app that requires that level of authorization.
  • 僅當(dāng)用戶(hù)啟用需要該級(jí)別授權(quán)的應(yīng)用程序功能時(shí),才調(diào)用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.

  • 除非您立即需要用戶(hù)的位置或在后臺(tái)啟動(dòng)以接收位置更新策肝,否則請(qǐng)勿在啟動(dòng)時(shí)請(qǐng)求授權(quán)。

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.

  • 您需要在應(yīng)用程序的Info.plist文件中包含NSLocationWhenInUseUsageDescription和NSLocationAlwaysAndWhenInUseUsageDescription鍵隐绵。 (如果您的應(yīng)用支持iOS 10及更早版本之众,則還需要NSLocationAlwaysUsageDescription鍵。)如果這些鍵不存在依许,則授權(quán)請(qǐng)求會(huì)立即失敗棺禾。

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顯示了一種最初啟用應(yīng)用程序位置服務(wù)的方法。 如果您的應(yīng)用程序的授權(quán)狀態(tài)已經(jīng)確定峭跳,則無(wú)需申請(qǐng)授權(quán)膘婶。 如果您的應(yīng)用程序的授權(quán)狀態(tài)未確定缺前,請(qǐng)嘗試將初始授權(quán)請(qǐng)求限制為使用中授權(quán)。 如果您的應(yīng)用需要相應(yīng)的位置服務(wù)竣付,您可以立即請(qǐng)求授權(quán)诡延,但要準(zhǔn)備好讓用戶(hù)僅授予使用中授權(quán)或完全拒絕您的請(qǐng)求。

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及更高版本中古胆,如果您最初僅請(qǐng)求使用中授權(quán)肆良,則可以稍后調(diào)用requestAlwaysAuthorization()方法(如清單2所示)以升級(jí)應(yīng)用程序的授權(quán)級(jí)別。 請(qǐng)求始終授權(quán)時(shí)逸绎,系統(tǒng)將顯示存儲(chǔ)在Info.plist文件的NSLocationAlwaysAndWhenInUseUsageDescription鍵中的使用情況說(shuō)明字符串惹恃。 然后,用戶(hù)必須選擇是否授予始終授權(quán)的請(qǐng)求棺牧,或者讓您的應(yīng)用程序使用何時(shí)授權(quán)巫糙。 系統(tǒng)允許您的應(yīng)用僅升級(jí)其授權(quán)級(jí)別一次,在您執(zhí)行時(shí)向用戶(hù)顯示適當(dāng)?shù)慕缑妗?后續(xù)嘗試不顯示系統(tǒng)界面颊乘,也不會(huì)更改應(yīng)用程序的授權(quán)級(jí)別参淹。

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.

  • 當(dāng)您請(qǐng)求授權(quán)或應(yīng)用程序的授權(quán)狀態(tài)發(fā)生更改時(shí),請(qǐng)使用委托對(duì)象的locationManager(_:didChangeAuthorization :)方法來(lái)處理更改乏悄。 清單3顯示了該方法的實(shí)現(xiàn)浙值,該方法根據(jù)應(yīng)用程序的當(dāng)前授權(quán)級(jí)別啟用或禁用功能。

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.

  • 位置服務(wù)的可用性可能隨時(shí)發(fā)生變化檩小。 用戶(hù)可以在系統(tǒng)設(shè)置中禁用位置服務(wù)开呐,無(wú)論是專(zhuān)門(mén)針對(duì)您的應(yīng)用還是針對(duì)所有應(yīng)用。 當(dāng)設(shè)備進(jìn)入飛行模式時(shí)规求,位置服務(wù)也會(huì)被禁用筐付,當(dāng)設(shè)備離開(kāi)飛行模式時(shí),它們可能會(huì)恢復(fù)阻肿。 如果您的應(yīng)用程序在可用性狀態(tài)更改時(shí)正在運(yùn)行(在前臺(tái)或后臺(tái))瓦戚,系統(tǒng)會(huì)調(diào)用您的locationManager(_:didChangeAuthorization :)方法來(lái)通知您更改。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末丛塌,一起剝皮案震驚了整個(gè)濱河市较解,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌姨伤,老刑警劉巖哨坪,帶你破解...
    沈念sama閱讀 206,126評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異乍楚,居然都是意外死亡当编,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)徒溪,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)忿偷,“玉大人金顿,你說(shuō)我怎么就攤上這事±鹎牛” “怎么了揍拆?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,445評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵,是天一觀(guān)的道長(zhǎng)茶凳。 經(jīng)常有香客問(wèn)我嫂拴,道長(zhǎng),這世上最難降的妖魔是什么贮喧? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,185評(píng)論 1 278
  • 正文 為了忘掉前任筒狠,我火速辦了婚禮,結(jié)果婚禮上箱沦,老公的妹妹穿的比我還像新娘辩恼。我一直安慰自己,他們只是感情好谓形,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評(píng)論 5 371
  • 文/花漫 我一把揭開(kāi)白布灶伊。 她就那樣靜靜地躺著,像睡著了一般寒跳。 火紅的嫁衣襯著肌膚如雪聘萨。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 48,970評(píng)論 1 284
  • 那天冯袍,我揣著相機(jī)與錄音匈挖,去河邊找鬼碾牌。 笑死康愤,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的舶吗。 我是一名探鬼主播征冷,決...
    沈念sama閱讀 38,276評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼誓琼!你這毒婦竟也來(lái)了检激?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 36,927評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤腹侣,失蹤者是張志新(化名)和其女友劉穎叔收,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體傲隶,經(jīng)...
    沈念sama閱讀 43,400評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡饺律,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了跺株。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片复濒。...
    茶點(diǎn)故事閱讀 37,997評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡脖卖,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出巧颈,到底是詐尸還是另有隱情畦木,我是刑警寧澤,帶...
    沈念sama閱讀 33,646評(píng)論 4 322
  • 正文 年R本政府宣布砸泛,位于F島的核電站十籍,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏唇礁。R本人自食惡果不足惜妓雾,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望垒迂。 院中可真熱鬧械姻,春花似錦、人聲如沸机断。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,204評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)吏奸。三九已至欢揖,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間奋蔚,已是汗流浹背她混。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,423評(píng)論 1 260
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留泊碑,地道東北人坤按。 一個(gè)月前我還...
    沈念sama閱讀 45,423評(píng)論 2 352
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像馒过,于是被迫代替她去往敵國(guó)和親臭脓。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評(píng)論 2 345