Last active
August 29, 2015 14:22
-
-
Save scotteg/eb8e9d655d9ab7ced257 to your computer and use it in GitHub Desktop.
Vends formatted address string for CLPlacemark or MKMapItem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Address { | |
static let zipPlus4RegEx = NSRegularExpression(pattern: "\\-\\d{4}", options: nil, error: nil)! | |
static func formattedAddressForPlacemark(placemark: CLPlacemark, includeName: Bool = true, withLineBreaks: Bool = true, showCountryIfUSA: Bool = false) -> String { | |
var addressArray = [String]() | |
var index = 0 | |
if placemark.name != nil && includeName { addressArray.append(placemark.name) } | |
if placemark.subLocality != nil { addressArray.append(placemark.subLocality) } // Neighborhood | |
let streetNumber = placemark.subThoroughfare != nil ? placemark.subThoroughfare + " " : "" | |
let streetName = placemark.thoroughfare | |
let streetAddress = "\(streetNumber)\(streetName)" | |
if count(streetAddress) > 0 { addressArray.append(streetAddress) } | |
let city = placemark.locality != nil ? placemark.locality : "" | |
let state = placemark.administrativeArea != nil ? city != nil ? ", " + placemark.administrativeArea : placemark.administrativeArea : "" | |
var postalCode = "" | |
if let placemarkPostalCode = placemark.postalCode { | |
let trimmedPostalCode = zipPlus4RegEx.stringByReplacingMatchesInString(placemarkPostalCode, options: nil, range: NSMakeRange(0, count(placemarkPostalCode)), withTemplate: "") | |
postalCode = state != "" ? " " + trimmedPostalCode : trimmedPostalCode | |
} | |
let localityAdministrativeAreaPostalCode = "\(city)\(state)\(postalCode)" | |
if count(localityAdministrativeAreaPostalCode) > 0 { addressArray.append(localityAdministrativeAreaPostalCode) } | |
if showCountryIfUSA && placemark.country != nil { addressArray.append(placemark.country) } | |
let orderedSet = NSOrderedSet(array: addressArray) | |
let separator = withLineBreaks ? "\n" : ", " | |
return separator.join(orderedSet.array as! [String]) | |
} | |
static func formattedAddressForMapItem(mapItem: MKMapItem, includeName: Bool = true, withLineBreaks: Bool = true, showCountryIfUSA: Bool = false) -> String { | |
let placemark = mapItem.placemark as CLPlacemark | |
return formattedAddressForPlacemark(placemark, includeName: includeName, withLineBreaks: withLineBreaks, showCountryIfUSA: showCountryIfUSA) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment