diff --git a/ContactsApp/ContactsViewController.swift b/ContactsApp/ContactsViewController.swift index 6876595..6568d60 100644 --- a/ContactsApp/ContactsViewController.swift +++ b/ContactsApp/ContactsViewController.swift @@ -27,7 +27,6 @@ class ContactsViewController: UIViewController { } func importContacts() { - let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactEmailAddressesKey, CNContactPhoneNumbersKey, CNContactImageDataKey] as [Any] let request = CNContactFetchRequest( keysToFetch: keys as! [CNKeyDescriptor]) request.sortOrder = CNContactSortOrder.givenName @@ -152,7 +151,26 @@ extension ContactsViewController: UISearchBarDelegate, UISearchDisplayDelegate, } + func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { + importContacts() + } + func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { - print(searchText) + var foundContacts = [ContactStruct]() + + if searchText == "" { + importContacts() + contactsTable.reloadData() + } else { + for indexContact in contactStructArray.indices{ + let contactFound = contactStructArray[indexContact].contacts.filter({$0.givenName.lowercased().contains(searchText.lowercased())}) + + if !contactFound.isEmpty { + foundContacts.append(ContactStruct(isExpanded: true, contacts: contactFound, letter: contactStructArray[indexContact].letter)) + } + } + contactStructArray = foundContacts + contactsTable.reloadData() + } } }