簡體   English   中英

在Swift中使用CLLocationManager獲取當前位置

[英]Getting current location using CLLocationManager in Swift

如何獲取我的iOS設備的當前位置?

蘋果似乎已經對如何獲取位置進行了更改,而我找不到最新的帖子。 我在下面親自回答了這個問題:

我找不到獲取當前位置的最新解決方案,所以這是我的操作方法。

我的消息來源是蘋果關於位置跟蹤和智能手表的示例代碼,稱為PotLocCoreLocationwithiPhoneandAppleWatchPotLocCoreLocationwithiPhoneandAppleWatchhttps : //github.com/robovm/apple-ios-samples/tree/master/PotLocCoreLocationwithiPhoneandAppleWatch

這是您在應用程序中要做的事情。

請注意,步驟2-6中的所有內容均在此要點中: https : //gist.github.com/JonMercer/75b3f45cda16ee5d1e0955b2492f66dd

  1. 在xcode的項目設置中,單擊capabilities選項卡(在general選項卡旁邊的選項卡中,您將其放入捆綁包標識符)。 然后打開Background Mode並啟用Location updates 編輯感謝@Rob:還將NSLocationWhenInUseUsageDescription添加到您的plist。 該值可以是您喜歡的任何值
  2. 在視圖控制器內部,擴展CLLocationManagerDelegate

     class YourClass: UIViewController, CLLocationManagerDelegate { 
  3. 實現這兩個功能

     /** 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).") } 
  4. 創建一個let manager = CLLocationManager()變量

  5. viewDidLoad()設置以下內容: manager.requestWhenInUseAuthorization()manager.allowsBackgroundLocationUpdates = truemanager.startUpdatingLocation()
  6. 為了停止跟蹤,請執行以下操作: manager.stopUpdatingLocation()manager.allowsBackgroundLocationUpdates = false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM