簡體   English   中英

Swift - 在函數之間設置值時獲取 nil 的問題

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

嗨,當我編寫一個簡單的位置接收類時,我似乎只能將 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

}

預先感謝您的幫助,因為我知道這會很簡單/愚蠢

事情需要時間,這只是一個理解問題 您正在前進,就好像開始獲取位置會立即為您提供位置。 但它沒有:

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的代碼很久以前sendLocationPost結束了,並且得到了nil

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM