一尘不染

如何在Swift中以字符串形式获取CNContact电话号码?

swift

我正在尝试检索所有联系人的姓名和电话号码,并将它们放入iOS中的Swift数组中。我到目前为止已经做到了:

func findContacts() -> [CNContact] {

    marrContactsNumber.removeAllObjects()
    marrContactsName.removeAllObjects()

    let store = CNContactStore()

    let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]

    let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)

    var contacts = [CNContact]()

    do {
        try store.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (let contact, let stop) -> Void in
            contacts.append(contact)

            self.marrContactsName.addObject(contact.givenName + " " + contact.familyName)

            self.marrContactsNumber.addObject(contact.phoneNumbers)

            print(contact.phoneNumbers)
    }
    catch let error as NSError {
        print(error.localizedDescription)
    }

    print(marrContactsName.count)
    print(marrContactsNumber.count)

    return contacts
}

完成后,将完全marrContactsName包含我所有联系人姓名的数组。即“ John
Doe”。但是,marrContactsNumber返回一个值数组,例如

[<CNLabeledValue: 0x158a19950: identifier=F831DC7E-5896-420F-AE46-489F6C14DA6E,
label=_$!<Work>!$_, value=<CNPhoneNumber: 0x158a19640: countryCode=us, digits=6751420000>>,
<CNLabeledValue: 0x158a19a80: identifier=ECD66568-C6DD-441D-9448-BDEDDE9A68E1,
label=_$!<Work>!$_, value=<CNPhoneNumber: 0x158a199b0: countryCode=us, digits=5342766455>>]

我想知道如何仅将电话号码作为字符串值即“ XXXXXXXXXX”来检索。基本上,如何调用数字值。谢谢!


阅读 445

收藏
2020-07-07

共1个答案

一尘不染

我找到了解决方案: (contact.phoneNumbers[0].value as! CNPhoneNumber).valueForKey("digits") as! String

2020-07-07