我正在尝试获取用户在Swift中的位置。使用下面的代码。但是当我打电话时
让currentloc = self.locationManager.location?.coordinate,它返回一个nil值。下面的代码位于脚本中的let currentloc行之上。
self.locationManager.delegate = self
self.locationManager.requestAlwaysAuthorization()
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
答案 0 :(得分:1)
请确保:
import Corelocation
+ import MapKit
。MKMapViewDelegate
和CLLocationManagerDelegate
let locationManager = CLLocationManager()
尝试:
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager. requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
添加以下委托方法以打印您的位置:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations.last!.coordinate)
}
答案 1 :(得分:0)
TLDR;
在模拟器上测试时,您必须提供默认位置,请在此处查看我的答案:https://stackoverflow.com/a/32887820/4887400