【发布时间】:2018-02-13 19:58:08
【问题描述】:
您好,当我编写一个简单的位置接收类时,我似乎只能将 nil 作为我的位置变量。我已经搜索了一段时间的堆栈溢出并尝试了许多解决方案,但我似乎无法修复它。
下面是我的代码。我正在尝试方法,一种是在我的 didUpdateLocations 方法的结构中设置变量。另一种只是更新一个变量userLocation。目前两者都只是给出我的 nil,我不知道为什么。
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
}
提前感谢您的帮助,因为我知道这将是一些简单/愚蠢的事情
【问题讨论】:
-
您何时何地致电
sendLocationPost? -
哪个先打印,nil 还是 non-nil?
-
@PhillipMills Mills 既然你提到了它,那么 nils 打印首先
-
有道理。在致电
didUpdateLocations之前,您不能假设位置已更新。
标签: ios swift delegates core-location cllocationmanager