iOS Contacts How to Fetch contact by phone Number

前端 未结 2 482
眼角桃花
眼角桃花 2021-02-02 01:49

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 = CN         


        
2条回答
  •  温柔的废话
    2021-02-02 02:21

    SWIFT 4 UPDATE

    1) Add to .plist

    NSContactsUsageDescription
    Our application needs to your contacts
    

    2) Request Authorization if you don't have it

    func requestAccess() {
    
        let store = CNContactStore()
        store.requestAccess(for: .contacts) { granted, error in
            guard granted else {
                DispatchQueue.main.async {
                   self.presentSettingsActionSheet()
                }
                return
            }
        }
    }
    
    func presentSettingsActionSheet() {
        let alert = UIAlertController(title: "Permission to Contacts", message: "This app needs access to contacts in order to ...", preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "Go to Settings", style: .default) { _ in
            let url = URL(string: UIApplicationOpenSettingsURLString)!
            UIApplication.shared.open(url)
        })
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        present(alert, animated: true)
    }
    

    2) Check Authorization Status if you ask for it before

        if CNContactStore.authorizationStatus(for: .contacts) == .authorized {
            getContacts()
    
        }
    

    3) Call Get Contacts

        var contacts = [CNContact]()
    
        func getContacts(){
    
        let contactStore = CNContactStore()
        let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey, CNContactImageDataAvailableKey, CNContactThumbnailImageDataKey]
        let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
        request.sortOrder = CNContactSortOrder.givenName
    
        do {
            try contactStore.enumerateContacts(with: request) {
                (contact, stop) in
                self.contacts.append(contact)
            }
        }
        catch {
            print("unable to fetch contacts")
        }
    }
    

    4) THIS IS THE FUNCTION TO GET THE CONTACT NAME OR BY NUMBER

        func getNameFromContacts(number: String) -> String {
        var contactFetched : CNContact
        var contactName = ""
        if contacts.count > 0 {
    
            let numberToBeCompared = number.components(separatedBy:CharacterSet.decimalDigits.inverted).joined(separator: "")
            for c in contacts {
                for n in c.phoneNumbers {
                    if let numberRetrived = n.value as? CNPhoneNumber {
                         let numberRetrivedFixed = numberRetrived.stringValue.components(separatedBy:CharacterSet.decimalDigits.inverted).joined(separator: "")
                        if numberRetrivedFixed.elementsEqual(numberToBeCompared){
                            contactName = c.givenName
                            // OR get the contact --> c
                     contactFetched = c
    
                        }
                    }
                }
            }
    
            return contactName
    
        } else {
            return ""
        }
    }
    

提交回复
热议问题