📅  最后修改于: 2023-12-03 15:39:39.430000             🧑  作者: Mango
本文将介绍如何获取当前设备的位置信息,并返回经纬度坐标和地址信息。
import CoreLocation
let locationManager = CLLocationManager()
// 请求一次定位权限
locationManager.requestWhenInUseAuthorization()
// 请求始终定位权限
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// 获取当前位置
let location = locations.first
// 获取经纬度坐标
let coordinate = location?.coordinate
// 获取地址信息
CLGeocoder().reverseGeocodeLocation(location!, completionHandler: { (placemarks, error) in
if error == nil {
let placemark = placemarks?.first
// 获取地址字符串
let address = "\(placemark?.country ?? ""), \(placemark?.locality ?? ""), \(placemark?.subLocality ?? ""), \(placemark?.thoroughfare ?? ""), \(placemark?.subThoroughfare ?? "")"
print("经度:\(coordinate!.longitude), 纬度:\(coordinate!.latitude), 地址:\(address)")
} else {
print(error?.localizedDescription ?? "")
}
})
}
locationManager.startUpdatingLocation()
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// 请求一次定位权限
locationManager.requestWhenInUseAuthorization()
// 设置CLLocationManagerDelegate
locationManager.delegate = self
// 开始定位
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// 获取当前位置
let location = locations.first
// 获取经纬度坐标
let coordinate = location?.coordinate
// 获取地址信息
CLGeocoder().reverseGeocodeLocation(location!, completionHandler: { (placemarks, error) in
if error == nil {
let placemark = placemarks?.first
// 获取地址字符串
let address = "\(placemark?.country ?? ""), \(placemark?.locality ?? ""), \(placemark?.subLocality ?? ""), \(placemark?.thoroughfare ?? ""), \(placemark?.subThoroughfare ?? "")"
// 打印位置信息
print("经度:\(coordinate!.longitude), 纬度:\(coordinate!.latitude), 地址:\(address)")
} else {
print(error?.localizedDescription ?? "")
}
})
}
}
通过上述步骤,即可获取设备当前位置的经纬度坐标和地址信息。