CLGeocoder in Swift - unable to return string when using reverseGeocodeLocation

前端 未结 1 1279
清酒与你
清酒与你 2021-01-07 01:03

I\'m attempting to use CLGeocoder to return the location of coordinates in a string. My code currently looks like this:

func getPlaceName(latitude: Double, l         


        
1条回答
  •  被撕碎了的回忆
    2021-01-07 01:24

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

    0 讨论(0)
提交回复
热议问题