我对此很陌生,但我一直在设法跌跌撞撞地获取我的 IOS 设备的当前位置...等等唯一的问题是,我似乎无法获取 GMSPlace保留分配给我在类顶部声明的属性,我计划在另一个函数中使用它。
当我在回调范围内运行打印语句时,它工作正常,但是当我似乎使用“queryPlace”中存储的值时,它会返回“nil”。我猜这是一个范围和生命周期问题,但我不确定我是否正确理解它。
这是我很难理解为什么它不保留“place”值的代码:
import UIKit
import CoreLocation
import GoogleMaps
import GooglePlaces
class GoogleMapSearchVC : UIViewController, CLLocationManagerDelegate {
var placeQuery: GMSPlace?
func loadCurrentPosition() {
print("Loading Positions and Coords")
// Invoke Callback method to get GMSPlacesLiklihood
placesClient.currentPlace(callback: { (placeLikelihoodList, error) -> Void in
if let error = error {
print("Pick Place error: \(error.localizedDescription)")
return
}
if let placeLikelihoodList = placeLikelihoodList {
let place = placeLikelihoodList.likelihoods.first?.place
if let place = place {
self.updateMap(newLocation: place)
// updateMap function moves camera to current location.
self.placeQuery = place
// If I print(self.placeQuery) here, it works fine, but later on placeQuery returns nil.
}
}
})
}
func doSomethingWithPlace() {
print(self.placeQuery?coordinate.latitude)
// Returns 'nil'
}
}
预先感谢您的帮助,非常感谢。
最佳答案
不,不应该有任何“终身”问题。 placeQuery
与 View Controller 实例的生命周期绑定(bind)。
只是一个愚蠢的猜测(很抱歉,如果这很明显):你确定doSomethingWithPlace()
回调返回后访问变量吗?由于您仅在异步回调中设置它,因此当 loadCurrentPosition()
时不会设置该变量。返回。
如果这不是问题,这里有一个调试提示,可以找出该值在哪里设置回 nil
:您可以在变量声明行设置断点,调试器将在 setter 中中断。如果您更喜欢“打印调试”,您还可以添加 didSet
子句:
var placeQuery: GMSPlace? {
didSet {
print("setting placeQuery from \(oldValue) to \(placeQuery)")
}
}
关于Swift:似乎无法将placesClient.currentPlace 的结果位置存储为类属性以在其他地方使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51994792/