iOS联系人如何通过电话号码获取联系人 [英] iOS Contacts How to Fetch contact by phone Number

查看:168
本文介绍了iOS联系人如何通过电话号码获取联系人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想通过电话号码联系姓名和姓氏。我试过这个,但这太慢了,cpu超过了%120。

I just want to get contact given name and family name by phone number. I tried this but this is too much slow and cpu is hitting over %120.

let contactStore = CNContactStore()
            let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]
            var contacts = [CNContact]()
            do {
                try contactStore.enumerateContactsWithFetchRequest(CNContactFetchRequest.init(keysToFetch: keys), usingBlock: { (contact, cursor) in
                    if (!contact.phoneNumbers.isEmpty) {
                        for phoneNumber in contact.phoneNumbers {
                            if let phoneNumberStruct = phoneNumber.value as? CNPhoneNumber {
                                do {
                                    let libPhone = try util.parseWithPhoneCarrierRegion(phoneNumberStruct.stringValue)
                                    let phoneToCompare = try util.getNationalSignificantNumber(libPhone)
                                    if formattedPhone == phoneToCompare {
                                        contacts.append(contact)
                                    }
                                }catch {
                                    print(error)
                                }
                            }

                        }
                    }
                })
                if contacts.count > 0 {
                    contactName = (contacts.first?.givenName)! + " " + (contacts.first?.familyName)!
                    print(contactName)
                    completionHandler(contactName)
                }
            }catch {
                print(error)
            }

当我使用phonenumber Kit查找联系人时,它会增加cpu并给出延迟响应。

Also When I Use phonenumber Kit for find contacts its increasing cpu and giving late response.

var result: [CNContact] = []
        let nationalNumber = PhoneNumberKit().parseMultiple([phoneNumber])
        let number = nationalNumber.first?.toNational()
        print(number)

        for contact in self.addressContacts {
            if (!contact.phoneNumbers.isEmpty) {

                let phoneNumberToCompareAgainst = number!.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
                for phoneNumber in contact.phoneNumbers {
                    if let phoneNumberStruct = phoneNumber.value as? CNPhoneNumber {
                        let phoneNumberString = phoneNumberStruct.stringValue
                        let nationalContactNumber = PhoneNumberKit().parseMultiple([phoneNumberString])
                        let nationalContactNumberString = nationalContactNumber.first?.toNational()
                        if nationalContactNumberString == number {
                            result.append(contact)
                        }
                    }
                }
            }
        }

        return result


推荐答案

您的实施问题是您访问地址簿在您正在进行的每次搜索中。

The problem with your implementation is that you access the address book in every search you are making.

如果您在第一次访问后将保留内存中的地址簿内容,则不会达到此高CPU使用率。

If instead you will hold in-memory the address book content after the first access you will not reach this high CPU usage.


  1. 首先在你的控制器中保存一个懒惰的var,它将保存addre ss书内容:

  1. First hold a lazy var in your controller that will hold the address book content:

lazy var contacts: [CNContact] = {
    let contactStore = CNContactStore()
    let keysToFetch = [
        CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),
        CNContactEmailAddressesKey,
        CNContactPhoneNumbersKey,
        CNContactImageDataAvailableKey,
        CNContactThumbnailImageDataKey]

    // Get all the containers
    var allContainers: [CNContainer] = []
    do {
        allContainers = try contactStore.containersMatchingPredicate(nil)
    } catch {
        print("Error fetching containers")
    }

    var results: [CNContact] = []

    // Iterate all containers and append their contacts to our results array
    for container in allContainers {
        let fetchPredicate = CNContact.predicateForContactsInContainerWithIdentifier(container.identifier)

        do {
             let containerResults = try     contactStore.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: keysToFetch)
            results.appendContentsOf(containerResults)
        } catch {
            print("Error fetching results for container")
        }
    }

    return results
}()




  1. 当您要查找具有特定电话号码的联系人时,请通过内存数组进行迭代:

   func searchForContactUsingPhoneNumber(phoneNumber: String) -> [CNContact] {
    var result: [CNContact] = []

    for contact in self.contacts {
        if (!contact.phoneNumbers.isEmpty) {
            let phoneNumberToCompareAgainst = phoneNumber.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
            for phoneNumber in contact.phoneNumbers {
                if let phoneNumberStruct = phoneNumber.value as? CNPhoneNumber {
                    let phoneNumberString = phoneNumberStruct.stringValue
                    let phoneNumberToCompare = phoneNumberString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
                    if phoneNumberToCompare == phoneNumberToCompareAgainst {
                        result.append(contact)
                    }
                }
            }
         } 
    }

    return result
}


我用非常大的地址簿测试了它,它运作顺畅。

这是整个视图控制器拼凑在一起以供参考。

Here is the entire view controller patched together for reference.

import UIKit
import Contacts

class ViewController: UIViewController {

    lazy var contacts: [CNContact] = {
        let contactStore = CNContactStore()
        let keysToFetch = [
                CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),
                CNContactEmailAddressesKey,
                CNContactPhoneNumbersKey,
                CNContactImageDataAvailableKey,
                CNContactThumbnailImageDataKey]

        // Get all the containers
        var allContainers: [CNContainer] = []
        do {
            allContainers = try contactStore.containersMatchingPredicate(nil)
        } catch {
            print("Error fetching containers")
        }

        var results: [CNContact] = []

        // Iterate all containers and append their contacts to our results array
        for container in allContainers {
            let fetchPredicate = CNContact.predicateForContactsInContainerWithIdentifier(container.identifier)

            do {
                let containerResults = try contactStore.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: keysToFetch)
                results.appendContentsOf(containerResults)
            } catch {
                print("Error fetching results for container")
            }
        }

        return results
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let contact = searchForContactUsingPhoneNumber("(555)564-8583")
        print(contact)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func searchForContactUsingPhoneNumber(phoneNumber: String) -> [CNContact] {

        var result: [CNContact] = []

        for contact in self.contacts {
            if (!contact.phoneNumbers.isEmpty) {
                let phoneNumberToCompareAgainst = phoneNumber.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
                for phoneNumber in contact.phoneNumbers {
                    if let phoneNumberStruct = phoneNumber.value as? CNPhoneNumber {
                        let phoneNumberString = phoneNumberStruct.stringValue
                        let phoneNumberToCompare = phoneNumberString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
                        if phoneNumberToCompare == phoneNumberToCompareAgainst {
                            result.append(contact)
                        }
                    }
                }
            }
        }

        return result
    }
}

我用 flohei的回答

这篇关于iOS联系人如何通过电话号码获取联系人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆