如何在 iOS 中获取当前位置的经纬度?

iosapps/applicationsmobile development更新于 2026/2/14 5:07:17

几乎所有应用程序都会使用位置服务,因此对位置有全面的了解至关重要。在本文中,我们将了解如何获取当前位置的经纬度。

为此,我们将使用 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 − 在 vi​​ewDidLoad 方法中编写以下代码

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)
      }
   }
}

相关文章