Myang
Myang

Reputation: 11

How to make alphabetical section with contacts in tableView in swift

I'm new to Swift and I have arrays made with CNContact(familyName, givenName, phoneNumber).

I'd like to make name contacts alphabetical order and group them in sections in order to put them in the "titleForHeaderInSection" as below.

iOS contacts screenshot

Does anyone know how to group and put it into titleForHeaderInSection??

struct AddressModel { 
    let nameAndPhone: [AddressContact]
}

struct AddressContact {
    let contact: CNContact
}

class AddressViewController: UITableViewController {

    var addressArray = [AddressModel]()

    private func fetchContacts() {
        print("Attempting to fetch contacts today")

        let store = CNContactStore()

        store.requestAccess(for: .contacts) { (granted, err) in
            if let err = err {
                print("Failed to request access:", err)
                return
            }
            if granted {
                let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey] as [Any]
                let request = CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])
                request.sortOrder = CNContactSortOrder.userDefault

                do {
                    var addressContact = [AddressContact]()
                    try store.enumerateContacts(with: request, usingBlock: { (contact, stop) in
                    addressContact.append(AddressContact(contact: contact))
                 })
                 let nameAndPhone = AddressModel(nameAndPhone: addressContact)
                 self.addressArray = [nameAndPhone] 
            } catch let err {
                print("Failed to enumerate contacts:", err)
            }
        } else {
            print("Access denied..")
        }
    }
}

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "Section \(section)"
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return self.addressArray.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.addressArray[section].nameAndPhone.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    let nameAndPhone = addressArray[indexPath.section].nameAndPhone[indexPath.row]

    let fullName = nameAndPhone.contact.familyName + nameAndPhone.contact.givenName
    cell.textLabel?.text = fullName
    return cell
}

Upvotes: 1

Views: 4064

Answers (2)

Ashish
Ashish

Reputation: 1

For sorting section title try the closure:

sectionTitle = sectionTitle.sorted(by: { $0 < $1 }) // First argument smaller then second argument.

Upvotes: 0

Shahrukh
Shahrukh

Reputation: 752

Try this

func sectionIndexTitles(for tableView: UITableView) -> [String]? {
  // ...
}

Upvotes: 1

Related Questions