How do i return coordinates after forward geocoding?

不问归期 提交于 2019-11-27 09:52:23

You are correct about the asynchronous issue. Basically, you cannot do anything after this code:

// [A1]
self.geocoder.geocodeAddressString(combinedAddress, completionHandler: {
    (placemarks, error) -> Void in
    // [B] ... put everything _here_
})
// [A2] ... nothing _here_

The reason is that the stuff inside the curly braces (B) happens later than the stuff outside it (including the stuff afterward, A2). In other words, the code in my schematic above runs in the order A1, A2, B. But you are dependent on what happens inside the curly braces, so you need that dependent code to be inside the curly braces so that it executes in sequence with the results of the geocoding.

Of course this also means that the surrounding function cannot return a result, because it returns before the stuff in curly braces has even happened. The code in my schematic goes A1, A2, return! Only later does B happen. So clearly you cannot return anything that happens in B because it hasn't happened yet.

Just pass the coordinate values obtained from the completionHandler to any other method and do what you like to do.

{
        self.placemarkLatitude = (placemark.location?.coordinate.latitude)! //THIS RETURNS A VALUE
        self.placemarkLongitude = (placemark.location?.coordinate.longitude)! //THIS RETURNS A VALUE

// After this code pass the values like,

passingTheCoordinates(placemarkLatitude, placemarkLongitude)

}


func passingTheCoordinates(latitude:CLLocationDegrees, _ longitude:CLLocationDegrees){

}

Did not have enough reputation to reply your question but I also have this same problem today. I don't know much about your app design but for my case (which is stuck at the same place like you, same func, same problem, can't save to variable). My solution (maybe kinda temporally, does not good) is to save (placemark.location?.coordinate.latitude)! and (placemark.location?.coordinate.longitude)! to CoreData as Double. This is how I implemented it. As I said before, since I don't know your app much so depend on your need, you might want something else.

LocationManager.sharedInstance.getReverseGeoCodedLocation(address: searchBar.text!, completionHandler: { (location:CLLocation?, placemark:CLPlacemark?, error:NSError?) in

    if error != nil {
        print((error?.localizedDescription)!)
        return
    }

    if placemark == nil {
        print("Location can't be fetched")
        return
    }

    //Saving geo code to Core Data
    newEntry.lat = (placemark?.location?.coordinate.latitude)!
    newEntry.long = (placemark?.location?.coordinate.longitude)!
})

Credit to this repo for the LocationManager.swift file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!