如何在 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)
}
}
}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP