嗨,我似乎只能将nil作为我的位置变量,而我正在编写一个简单的位置接收类。我已经搜索了堆栈溢出一段时间并尝试了很多解决方案,但我似乎无法修复它。
以下是我的代码。我尝试使用方法,一种是在didUpdateLocations方法中的结构中设置变量。另一种是更新变量userLocation。两者现在只是给我的零,我无法弄清楚原因。
class SendLocation: NSObject, CLLocationManagerDelegate{
var userLocation: CLLocation? = nil
var locationManager:CLLocationManager!
struct LocationStruct{
var latitude:CLLocationDegrees?, longitude:CLLocationDegrees?
}
var locationStruct = LocationStruct()
func sendLocationPost(){
determineCurrentLocation()
print(userLocation) // This is nil
print(locationStruct.latitude) // This is nil
print(locationStruct.longitude) // This is nil
}
func determineCurrentLocation(){
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
userLocation = locations[0] as CLLocation
print(userLocation) // This IS NOT nil
locationStruct.latitude=userLocation?.coordinate.latitude
locationStruct.longitude=userLocation?.coordinate.longitude
}
提前感谢您的帮助,因为我知道这将是简单/愚蠢的事情
答案 0 :(得分:0)
这只是理解事情需要时间的问题。你正在向前迈进,好像开始获得一个位置可以立即为你提供一个位置。但它没有:
-fdebug-prefix-map=$PWD=.
当您第一次拨打func sendLocationPost(){
determineCurrentLocation()
// so now things start... but they take _time_...!
print(userLocation) // This is nil
// because it's _too soon!_
// ...
}
时,传感器预热需要很长时间才能到达良好的位置:
determineCurrentLocation
最后,经过一些重要的时间,也许,也许,也许,我们终于开始得到一些更新,经过一段时间,也许他们不是零:
func determineCurrentLocation(){
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
// SLOWLY... things now start to happen
}
}
现在我们有一个位置。但与此同时,func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
userLocation = locations[0] as CLLocation
print(userLocation) // This IS NOT nil
locationStruct.latitude=userLocation?.coordinate.latitude
locationStruct.longitude=userLocation?.coordinate.longitude
}
中的代码很久以前就已结束,并获得了sendLocationPost
。