func getCurrectLocationInfo()-> String {
var strFormattedAddress : String = ""
locationManager.requestWhenInUseAuthorization()
var currentLoc: CLLocation!
if(CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways) {
currentLoc = locationManager.location
print(currentLoc.coordinate.latitude)
print(currentLoc.coordinate.longitude)
let latString = String(currentLoc.coordinate.latitude)
let longString = String(currentLoc.coordinate.longitude)
}
self.getaddress(pdblLatitude: latString, withLongitude: longString) { address in
print(address)
strFormattedAddress = address
return strFormattedAddress
}
}
如何异步返回用户的当前经纬度。请指导。在上面的代码中,它返回空字符串
由于函数是异步的,因此您需要使用完成块来修改函数,如下所示:
func getCurrectLocationInfo(completion: @escaping (String) -> Void) {
var strFormattedAddress : String = ""
locationManager.requestWhenInUseAuthorization()
var currentLoc: CLLocation!
if(CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways) {
currentLoc = locationManager.location
print(currentLoc.coordinate.latitude)
print(currentLoc.coordinate.longitude)
let latString = String(currentLoc.coordinate.latitude)
let longString = String(currentLoc.coordinate.longitude)
}
self.getaddress(pdblLatitude: latString, withLongitude: longString) { address in
print(address)
strFormattedAddress = address
completion(strFormattedAddress)
}
}