Swift - Generate an Address Format from Reverse Geocoding

前端 未结 10 1423
难免孤独
难免孤独 2021-01-31 03:46

I am trying to generate a Formatted Full address using CLGeocoder in Swift 3. I referred to this SO thread to get the code given below.

However, sometimes the app crashe

10条回答
  •  难免孤独
    2021-01-31 04:43

    This is my code for swift 3

    func getAdressName(coords: CLLocation) {
    
        CLGeocoder().reverseGeocodeLocation(coords) { (placemark, error) in
                if error != nil {
                    print("Hay un error")
                } else {
    
                    let place = placemark! as [CLPlacemark]
                    if place.count > 0 {
                        let place = placemark![0]
                        var adressString : String = ""
                        if place.thoroughfare != nil {
                            adressString = adressString + place.thoroughfare! + ", "
                        }
                        if place.subThoroughfare != nil {
                            adressString = adressString + place.subThoroughfare! + "\n"
                        }
                        if place.locality != nil {
                            adressString = adressString + place.locality! + " - "
                        }
                        if place.postalCode != nil {
                            adressString = adressString + place.postalCode! + "\n"
                        }
                        if place.subAdministrativeArea != nil {
                            adressString = adressString + place.subAdministrativeArea! + " - "
                        }
                        if place.country != nil {
                            adressString = adressString + place.country!
                        }
    
                        self.lblPlace.text = adressString
                    }
                }
            }
      }
    

    You can esaily call above funcation like:

    let cityCoords = CLLocation(latitude: newLat, longitude: newLon)
    cityData(coord: cityCoords)
    

提交回复
热议问题