[英]Getting current location using CLLocationManager in Swift
如何獲取我的iOS設備的當前位置?
蘋果似乎已經對如何獲取位置進行了更改,而我找不到最新的帖子。 我在下面親自回答了這個問題:
我找不到獲取當前位置的最新解決方案,所以這是我的操作方法。
我的消息來源是蘋果關於位置跟蹤和智能手表的示例代碼,稱為PotLocCoreLocationwithiPhoneandAppleWatch
和PotLocCoreLocationwithiPhoneandAppleWatch
: https : //github.com/robovm/apple-ios-samples/tree/master/PotLocCoreLocationwithiPhoneandAppleWatch
這是您在應用程序中要做的事情。
請注意,步驟2-6中的所有內容均在此要點中: https : //gist.github.com/JonMercer/75b3f45cda16ee5d1e0955b2492f66dd
capabilities
選項卡(在general
選項卡旁邊的選項卡中,您將其放入捆綁包標識符)。 然后打開Background Mode
並啟用Location updates
。 編輯感謝@Rob:還將NSLocationWhenInUseUsageDescription
添加到您的plist。 該值可以是您喜歡的任何值 在視圖控制器內部,擴展CLLocationManagerDelegate
class YourClass: UIViewController, CLLocationManagerDelegate {
實現這兩個功能
/** Increases that location count by the number of locations received by the manager. Updates the batch count with the added locations. */ func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //use the "locations" variable here } /// Log any errors to the console. func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("Error occured: \\(error.localizedDescription).") }
創建一個let manager = CLLocationManager()
變量
viewDidLoad()
設置以下內容: manager.requestWhenInUseAuthorization()
, manager.allowsBackgroundLocationUpdates = true
和manager.startUpdatingLocation()
manager.stopUpdatingLocation()
和manager.allowsBackgroundLocationUpdates = false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.