jayn
jayn

Reputation: 45

CNContacts -- Address Line 2

How do we get the address line 2 for a specific contact address. I am able to successfully get the address line 1 using

cnContact.postalAddresses.first?.value.street

What property do we use to get the address line 2?

Also, how do we prioritize the home address to be displayed rather than the work address? Is this possible?

Upvotes: 2

Views: 699

Answers (2)

Rob
Rob

Reputation: 438232

If you want to sort the addresses in a particular order, you can do something like:

let addresses = contact.postalAddresses.sorted { (address1, address2) -> Bool in
    return self.labelOrder(address1.label) < self.labelOrder(address2.label)
}

Where

let labelPreferredOrder = [CNLabelHome, CNLabelWork, CNLabelPhoneNumberMobile, CNLabelPhoneNumberiPhone]

private func labelOrder(_ label: String?) -> Int {
    if let label = label, let index = labelPreferredOrder.index(of: label) {
        return index
    }
    return labelPreferredOrder.count + 1
}

You might want to add some hard coded label prefixes, too, in case user used their own hard-coded values, or if the contacts may have been imported from third-party source that didn't employ the localized, standard contacts prefixes:

let labelPreferredOrder = [CNLabelHome, "Home", "home", CNLabelWork, "Work", "work", CNLabelPhoneNumberMobile, "Mobile", "mobile", "Cell", "cell", CNLabelPhoneNumberiPhone]

Bottom line, sort these any way you want. Note, you don't need the phone-related labels for addresses, but you might include them in case you want to sort phone numbers using a similar technique.


To get the lines of the street address in an array (where you can fetch line 1 and line 2 separately, split it by \n:

let streetLines = address.value.street.split(separator: "\n")

Then a two line street address would be rendered as an array of strings

["123 Main Street", "Suite 100"]

Upvotes: 2

San Lewy
San Lewy

Reputation: 136

postalAddresses.first?.value.street is the full (line 1 and, if present, line 2) of the FIRST postalAddress in an ARRAY of postalAddresses for a Contact (cnContact). It is not, as you state, "line 1".

Upvotes: 1

Related Questions