如何在Swift (CLLocationManager)中获取用户当前坐标?
大家好!我是iOS开发新手,一直搞不懂如何获取用户当前的位置。我需要获取纬度和经度,以便之后发送到服务器。我已经导入了CoreLocation,在Info.plist中添加了键(NSLocationWhenInUseUsageDescription),写了代码,但坐标总是返回nil或nil。这是我的代码:
```swift
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
if let location = locationManager.location {
print("Lat: \(location.coordinate.latitude)")
print("Lon: \(location.coordinate.longitude)")
} else {
print("Location is nil")
}
}