异步返回用户的经度

问题描述 投票:0回答:1
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
    }
}

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

ios xcode cllocationmanager
1个回答
0
投票

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

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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.