如何在 iOS 中獲取當前位置的經緯度?


幾乎所有應用程式都使用定位服務,因此全面瞭解定位是必要的。在這篇文章中,我們將瞭解如何獲取當前位置的經緯度。

為此,我們將使用 CLLocationManager,您可以在此處閱讀更多相關資訊https://developer.apple.com/documentation/corelocation/cllocationmanager

我們將開發一個示例應用程式,在其中我們將使用者經緯度列印在 viewDidLoad 方法中,或者根據需要在 UILabel 上點選按鈕時列印。

所以讓我們開始吧,

步驟 1 − 開啟 Xcode → 新建專案 → 單檢視應用程式 → 讓我們將其命名為“Location”

步驟 2 − 開啟 info.plist 檔案並新增以下鍵。

<key>NSLocationWhenInUseUsageDescription</key>

<string>應用程式想要使用您的位置</string>

<key>NSLocationAlwaysUsageDescription</key>

<string>應用程式想要使用您的位置</string>

每當您進行與位置相關的操作時,都需要這些鍵,我們需要詢問使用者的許可權。

步驟 3 − 在 ViewController.swift 中,

import CoreLocation

步驟 4 − 建立 CLLocationManager 的物件

var locationManager = CLLocationManager()

步驟 5 − 在 viewDidLoad 方法中編寫以下程式碼,

locationManager.requestWhenInUseAuthorization()
var currentLoc: CLLocation!
if(CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways) {
   currentLoc = locationManager.location
   print(currentLoc.coordinate.latitude)
   print(currentLoc.coordinate.longitude)
}

此處“requestWhenInUseAuthorization”表示請求在應用程式處於前臺時使用定位服務的許可權。

步驟 6 − 執行應用程式以獲取經緯度,查詢完整程式碼

import UIKit
import CoreLocation
class ViewController: UIViewController {
   var locationManager = CLLocationManager()
   override func viewDidLoad() {
      super.viewDidLoad()
      locationManager.requestWhenInUseAuthorization()
      var currentLoc: CLLocation!
      if(CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
      CLLocationManager.authorizationStatus() == .authorizedAlways) {
         currentLoc = locationManager.location
         print(currentLoc.coordinate.latitude)
         print(currentLoc.coordinate.longitude)
      }
   }
}

更新於: 2019-07-30

3K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.