ios - 如何获取联系方式(名字、姓氏、联系人 ID、电话号码)

标签 ios swift ios8 ios9

我使用了 AddessBook 库(适用于 ios8)来获取所有联系人(名字、姓氏、contactId、所有电话号码)。它在模拟器上完美运行。

我的代码:

private func getContacts()->[Person] {

    var peapleOfContact: [Person] = []

    if !self.determineStatus() {
        return peapleOfContact
    }

    if let people = ABAddressBookCopyArrayOfAllPeople(self.adbk)?.takeRetainedValue() as? NSArray {
        for person in people{
            let contactID = ABRecordGetRecordID(person)
            let firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty).takeRetainedValue() as! String
            let lastName = ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue() as! String
            let personOfContact = Person(id: String(contactID), firstName: firstName, lastName: lastName)
            let numbers:ABMultiValue = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue()
            for ix in 0 ..< ABMultiValueGetCount(numbers) {
                let type = ABMultiValueCopyLabelAtIndex(numbers,ix).takeRetainedValue() as String
                let number = ABMultiValueCopyValueAtIndex(numbers,ix).takeRetainedValue() as! String
                let cleaned = self.removeSpecialCharsFromString(type)
                let shortNumber = self.makeSpecialShortNumberFromString(number)
                let phone = Number(number: number, short: shortNumber, type: cleaned)
                personOfContact.addPhoneNumber(phone)
            }
            peapleOfContact.append(personOfContact)
        }

    }
    return peapleOfContact
}

当xcode 7.1.1更新并使用ios9时,该库不起作用,因此使用ContactUI Framework。

我的代码:

private func getContact(){

    let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),
        CNContactImageDataKey,
        CNContactPhoneNumbersKey]

    let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)

    do {
        try store.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (let contact, let stop) -> Void in
            self.contacts.append(contact)
        })
    }
    catch let error as NSError {
        print(error.localizedDescription)
    }
}

并像这样使用:

self.getContact()
    for contact in self.contacts{
        print("Full name: \(CNContactFormatter.stringFromContact(contact, style: .FullName))")
        print("Give name: \(contact.givenName)")
        print("fimily name: \(contact.familyName)")
        print("Idnetifier name: \(contact.identifier)")

        for phoneNo in contact.phoneNumbers {
            if phoneNo.label == CNLabelPhoneNumberMobile {
                let number = (phoneNo.value as! CNPhoneNumber).stringValue
                print("Phone Number: \(number)")
            }
        }
    }

但未找到 contactId。如何获取 contactId ?如何使用ContactUI框架? 告诉我。谢谢

最佳答案

在 iOS 9.* 中,有一个名为“联系人”的新框架

用法:

import Contacts

    var validContacts: [CNContact] = []
    let contactStore = CNContactStore()

    // Request for contact access
    contactStore.requestAccessForEntityType(.Contacts) { (granted, e) -> Void in

        if granted {

            do {                    
                // Specify the key fields that you want to be fetched.
                // Note: if you didn't specify your specific field request. your app will crash
                let fetchRequest = CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey, CNContactMiddleNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactThumbnailImageDataKey])

                try contactStore.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (contact, error) -> Void in

                    // Lets filter (optional)
                    if !contact.emailAddresses.isEmpty || !contact.phoneNumbers.isEmpty {
                        validContacts.append(contact)
                    }
                })

                print(validContacts)
            }catch let e as NSError {
                print(e)
            }
        }
    }

解析:

    // Loop through contatcs
        for contact in validContacts {

            var phoneNumbers: [String] = []
            for phoneNumber in contact.phoneNumbers {
                let value = phoneNumber.value as! CNPhoneNumber
                phoneNumbers.append(value.stringValue)
            }

            var emailAddresses: [String] = []
            for emailAddress in contact.emailAddresses {
                let value = emailAddress.value as! String
                emailAddresses.append(value)
            }

            if let imageData = contact.imageData {
                let image = UIImage(data: imageData)

                print("image: \(image)")
            }

            // Lets log
            print("givenName: \(contact.givenName), middleName: \(contact.middleName), familyName: \(contact.familyName), phoneNumbers: \(phoneNumbers), emailAddresses: \(emailAddresses)\n")
        }

我有一个实现此功能的示例项目。 GitHub

关于ios - 如何获取联系方式(名字、姓氏、联系人 ID、电话号码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34178229/

相关文章:

ios - 在字典内的数组中追加 int

ios - iOS 中的 React Native 60 及以上边距问题 - 忽略虚假层大小

ios - 组合框架更新 UI 无法正常工作

objective-c - UIActivityViewController的completionHandler替换

swift - 对数组索引的操作

ios - 如何在我的 iOS 应用程序中处理保存数据?

objective-c - 对象在 presentModalViewController 之后返回 null

swift - 无法从 UITableViewCell 调用 PerformSegueWithIdentifier

ios - iOS 上的 Firebase 引用

ios - NSCache objectForKey : always return nil after memory warning on iOS 8