我有一个简单的按钮,当我按下这个按钮时,我调用了另一个类,我的location类来获取用户的当前位置。获得位置后,我想要更新标签文本,我必须显示位置。
这是我的location类:
class LocationManager: NSObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
var geoCoder = CLGeocoder()
var userAddress: String?
override init() {
super.init()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.activityType = .other
locationManager.requestWhenInUseAuthorization()
}
func getUserLocation(completion: @escaping(_ result: String) -> ()){
if CLLocationManager.locationServicesEnabled(){
locationManager.requestLocation()
}
guard let myResult = self.userAddress else { return }
completion(myResult)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
let userLocation: CLLocation = locations[0] as CLLocation
geoCoder.reverseGeocodeLocation(userLocation) { (placemarks, err) in
if let place = placemarks?.last{
self.userAddress = place.name!
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}
这就是我调用方法并更新标签的地方:
func handleEnter() {
mView.inLabel.isHidden = false
location.getUserLocation { (theAddress) in
print(theAddress)
self.mView.inLabel.text = "\(theAddress)"
}
}
我的问题是,当我单击我的按钮(并触发handleEnter())时,没有任何反应,就像它不会注册点击一样。只有在第二次点击之后,我才得到地址和标签的更新。我尝试添加打印,并使用断点来查看第一次点击是否注册,并且它注册了。我知道位置可能需要几秒钟才能返回带有地址的答案,我等待了,但仍然没有,只是在第二次点击后才显示出来。
似乎在第一次点击时,它还没有得到地址。当我获得地址时如何“通知”,然后尝试更新标签?
发布于 2019-06-21 20:02:26
由于didUpdateLocations
和reverseGeocodeLocation
方法是异步调用的,因此此guard
可能返回nil
地址的截止日期
guard let myResult = self.userAddress else { return }
completion(myResult)
这不会触发更新标签所需的完成,相反,您需要
var callBack:((String)->())?
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
let userLocation: CLLocation = locations[0] as CLLocation
geoCoder.reverseGeocodeLocation(userLocation) { (placemarks, err) in
if let place = placemarks?.last{
callBack?(place.name!)
}
}
}
然后使用
location.callBack = { [weak self] str in
print(str)
DispatchQueue.main.async { // reverseGeocodeLocation callback is in a background thread
// any ui
}
}
https://stackoverflow.com/questions/56709683
复制相似问题