2016-05-24 2 views
2

EDIT РЕШЕНИЕ: Как я и подозревал reverseGeocodeLocation асинхронный, так что я должен был использоватьКак я могу использовать данные из reverseGeocodeLocation в swift?

dispatch_async(
      dispatch_get_main_queue(), { 
       self.newAddress = address 
     }) 

Вы также должны ждать, пока переменная newAddress не обновляется, чтобы использовать его. Существует некоторое отставание, но это типичное время, примерно через секунду.

ORIGINAL:

Я пытаюсь использовать строку из CLGeocoder().reverseGeocodeLocation послать к другому виду, когда аннотация на карте нажата. Однако обработчик существует в закрытии и его Void in. Я пробовал String in, но это не согласуется с протоколом.

Есть ли способ использовать данные из крышки?

Код для обратного геокодирования

func getReversedGeocodeLocation(){ 
    CLGeocoder().reverseGeocodeLocation(newMeetupLocation, completionHandler: {(placemarks, error) -> Void in 


     if error != nil { 
      print("Reverse geocoder failed with error" + error!.localizedDescription) 
      return 
     } 

     if placemarks != nil { 
      if placemarks!.count > 0 { 
       let pm = placemarks![0] 
       self.name = pm.name! + "-" + pm.thoroughfare! 
      } 

     } 
     else { 
      print("Problem with the data received from geocoder") 
     } 
    }) 
} 
+0

Вы можете разместить больше кода? Вы пытаетесь отправить строку адреса? – chickenparm

+0

добавил код. Мне просто нужно выяснить, как получить данные из закрытия. Я хочу иметь возможность использовать строку адреса. – ggworean

ответ

1

Является ли это то, что вы пытаетесь достичь?

func getReversedGeocodeLocation(){ 
     CLGeocoder().reverseGeocodeLocation(newMeetupLocation, completionHandler: {(placemarks, error) -> Void in 


      if error != nil { 
       print("Reverse geocoder failed with error" + error!.localizedDescription) 
       return 
      } 

      if placemarks != nil { 
       if placemarks!.count > 0 { 
        let pm = placemarks![0] 
        let myAddress = pm.name! + "-" + pm.thoroughfare! 
        // just pass the address along, ie 
        self.newAddressFromGeocode(myAddress) 
       } 

      } 
      else { 
       print("Problem with the data received from geocoder") 
      } 
     }) 
    } 

    func newAddressFromGeocode(address:String) { 
     print(address) 
     // this is called from the completion handler 
     // do what you like here ie perform a segue and pass the string along 
    } 
0

Вы могли бы попробовать что-то вроде этого:

// add a variable outside the function. Once this is filled with the address you can pass it in your prepareForSegue 
var addresssFromPlacemark = "" 

func getReversedGeocodeLocation(){ 
    CLGeocoder().reverseGeocodeLocation(newMeetupLocation, completionHandler: {(placemarks, error) -> Void in 


     if error != nil { 
      print("Reverse geocoder failed with error" + error!.localizedDescription) 
      return 
     } 

     if placemarks != nil { 
      if placemarks!.count > 0 { 
       let placemark = placemarks![0] 
       var line = "" 

       // Format placemark into a string 
       line.addText(placemark.name) 
       line.addText(placemark.subThoroughfare, withSeparator: ", ") 
       if placemark.subThoroughfare != nil { 
       line.addText(placemark.thoroughfare, withSeparator: " ") 
       } else { 
       line.addText(placemark.thoroughfare, withSeparator: ", ") 
       } 
       line.addText(placemark.locality, withSeparator: ", ") 
       line.addText(placemark.administrativeArea, withSeparator: ", ") 
       line.addText(placemark.postalCode, withSeparator: ", ") 
       line.addText(placemark.country, withSeparator: ", ") 
       self.addressFromPlacemark = line 
      } 

     } 
     else { 
      print("Problem with the data received from geocoder") 
     } 
    }) 
} 
+0

Я попытался сменить переменную изнутри, но она не обновляется. Что-то связано с его асинхронностью – ggworean

+0

Вы уверены, что код вызывается? Добавьте печать («Сделано так далеко») под вашим кодом пусть pm = метки! [0] – chickenparm

+0

Да, я могу печатать в закрытии, но это насколько это возможно. Даже делая метод с другого плаката, где я вызываю метод, он не обновляется. – ggworean

Смежные вопросы