Return 异步获取用户的经纬度

Return user's latitude and longitude asynchronously

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
    }
}

如何异步return用户当前的经纬度。请指导。在上面的代码中,它是 returning 空字符串

由于该函数是异步的,您需要使用完成块修改您的函数,如下所示:

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)
    }
}

你需要这样称呼它:

LocationManager.shared.getCurrectLocationInfo) { locationInfo in 
    strPlaceSearched = locationInfo
}