Swift - 在函数之间设置值时出现 nil 问题

Swift - Trouble with getting nil when setting values in between functions

你好,我在编写一个简单的位置接收 class 时,似乎只能将 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

}

提前感谢您的帮助,因为我知道这将是一些事情simple/silly

这只是理解的问题,事情需要时间。你正在奋进,就好像开始获得一个位置一样,你会立即得到一个位置。但事实并非如此:

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 中的代码早就结束了,并得到了 nil.