我已成功编写了一个搜索用户联系人的程序,但效果非常低效。它使用嵌套的for和if语句,整体上非常混乱。当我在我的模拟器上运行时,它运行正常,但速度很慢。
有谁知道更好的方式来写这个?
这就是我目前所拥有的:
import UIKit
import Contacts
class ChatViewController: UIViewController {
@IBOutlet weak var contactTextField: UITextField!
@IBOutlet weak var contactNameView: UIView!
let contactStore = CNContactStore()
var contacts = [CNContact]()
let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey] as [Any]
@IBAction func contactTextFieldChanged(_ sender: Any) {
if contactTextField.text != nil {
contactTableView.isHidden = false
let request = CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])
do {
try contactStore.enumerateContacts(with: request){
(contact, stop) in
self.contacts.append(contact)
for familyName in contact.familyName{
for givenName in contact.givenName{
for phoneNumber in contact.phoneNumbers {
if String(describing: phoneNumber) != ""{
if String(describing: phoneNumber) == self.contactTextField.text || String(describing: givenName) == self.contactTextField.text || String(describing: familyName) == self.contactTextField.text{
if let number = phoneNumber.value as? CNPhoneNumber, let label = phoneNumber.label {
let localizedLabel = CNLabeledValue<CNPhoneNumber>.localizedString(forLabel: label)
print("\(contact.givenName) \(contact.familyName) tel:\(localizedLabel) -- \(number.stringValue)")
}
}
}
}
}
}
}
print(contacts)
} catch {
print("unable to fetch contacts")
}
}
}
}