0

I'll make function of returning address String. But below function return empty String of "".

How make return address function?

    let defaultLocation = CLLocation(latitude: 35.17944, longitude: 129.07556)

    func convertToPlaceMark(_ location: CLLocation, data: Any?) -> String {
            var str: String? = ""
        CLGeocoder().reverseGeocodeLocation(location) {
               places,err in 

               if err != nil {
                  print("geocoder error")
                  return
               }
               let placeMark1: CLPlacemark? = places!.last
               if placeMark1 != nil {
                    str = placeMark1?.name     // "1001 Jungang-daero\n" <--- I need function that return this value
                    print(str!)
                }
          }
         return str!
     }

     print(convertToPlaceMark(defaultLocation, data: nil)) // "\n"
koreaMacGuy
  • 75
  • 2
  • 8

1 Answers1

2

yes, this function always return empty string, coz CLGeocoder().reverseGeocodeLocation(location) take time to get address from Location and at same time your return str! also execute so you get empty string.

use closure to get address from location.

func convertToPlaceMark(_ location: CLLocation, _ handler: @escaping ((String?) -> Void)) {

       CLGeocoder().reverseGeocodeLocation(location) {
           places,err in

           if err != nil {
               print("geocoder error")
               handler(nil)
               return
           }
           let placeMark1: CLPlacemark? = places!.last
           handler(placeMark1?.name)
       }
   }

Usage

convertToPlaceMark(location) { (address) in
        if let address = address {
            print(address)
        }
    }
Pratik Prajapati
  • 1,137
  • 1
  • 13
  • 26
  • thx for ur answer, But I do not need ur answer, Because ur code is same like code without handler. at all results address value do not need to insert handler parameter. not right? – koreaMacGuy Jan 27 '20 at 06:38
  • if you do not use closure than you'll always get empty string or if you call function in main thread might you ui will freeze for moment. – Pratik Prajapati Jan 27 '20 at 06:43
  • i know ur mean... But also handler was not useful. Because i need return value function, not set function. – koreaMacGuy Jan 27 '20 at 06:58
  • I think this is the right approach. @macmini you need to learn how completion handler works but also look at the accepted answer in the question that I think your question is a duplicate of – Joakim Danielson Jan 27 '20 at 07:53