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

How to return the current lat long of the user asynchronously. Please guide. Here in above code it is returning empty string

Frankenstein
  • 14,749
  • 4
  • 18
  • 44
iPhone 7
  • 1,581
  • 1
  • 23
  • 58

1 Answers1

0

Since the function is asynchronous, you need to modify your function with a completion block, like this:

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

And you need to call it like this:

LocationManager.shared.getCurrectLocationInfo) { locationInfo in 
    strPlaceSearched = locationInfo
}
Frankenstein
  • 14,749
  • 4
  • 18
  • 44