CLGeocoder in Swift - unable to return string when using reverseGeocodeLocation

不想你离开。 提交于 2019-12-01 00:50:14

Since reverseGeocodeLocation is an asynchronous function, you need to make your getPlaceName function pass the answer back via a block instead of a return statement. Example:

func getPlaceName(latitude: Double, longitude: Double, completion: (answer: String?) -> Void) {

   let coordinates = CLLocation(latitude: latitude, longitude: longitude)

   CLGeocoder().reverseGeocodeLocation(coordinates, completionHandler: {(placemarks, error) -> Void in
       if (error != nil) {
           println("Reverse geocoder failed with an error" + error.localizedDescription)
           completion(answer: "")
       } else if placemarks.count > 0 {
           let pm = placemarks[0] as CLPlacemark
           completion(answer: displayLocaitonInfo(pm))
       } else {
           println("Problems with the data received from geocoder.")
           completion(answer: "")
       }
   })

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