Swift - Generate an Address Format from Reverse Geocoding

前端 未结 10 1424
难免孤独
难免孤独 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:22

    CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: vehicleLocation.latitude, longitude: vehicleLocation.latitude), completionHandler: {(placemarks, error) -> Void in
    
      guard error == nil else {completionHandler(nil); return}
    
      guard let place = placemarks else {completionHandler(nil); return}
    
      if place.count > 0 {
        let pm = place[0]
    
        var addArray:[String] = []
        if let name = pm.name {
          addArray.append(name)
        }
        if let thoroughfare = pm.thoroughfare {
          addArray.append(thoroughfare)
        }
        if let subLocality = pm.subLocality {
          addArray.append(subLocality)
        }
        if let locality = pm.locality {
          addArray.append(locality)
        }
        if let subAdministrativeArea = pm.subAdministrativeArea {
          addArray.append(subAdministrativeArea)
        }
        if let administrativeArea = pm.administrativeArea {
          addArray.append(administrativeArea)
        }
        if let country = pm.country {
          addArray.append(country)
        }
        if let postalCode = pm.postalCode {
          addArray.append(postalCode)
        }
    
        let addressString = addArray.joined(separator: ",\n")
    
        print(addressString)
    
        completionHandler(addressString)
      }
      else { completionHandler(nil)}
    })
    

提交回复
热议问题