1

我正在使用从 iOS 电话簿中检索联系人的新版本。第一个查询返回的唯一标识符有问题。通常唯一标识符是一个 UUID,但有时会附加“:ABPerson”。使用此标识符查询电话簿 API 有时可行,但并非总是如此。有谁知道,是否有办法避免这种行为?目前,我尝试保护两个查询。第一个是按原样使用标识符,第二个(如果第一个失败)是使用剥离“:ABPerson”扩展名的标识符。

使用的第一个查询是:

class func getAllPhoneBookContacts() -> [PhonebookContact] {
    let contactStore = CNContactStore()
    var contacts = [PhonebookContact]()
    PhoneBookContactsHelper.requestForAccess { (accessGranted) -> Void in
        if accessGranted {
            let keys = [CNContactIdentifierKey, CNContactPhoneNumbersKey]

            do {
                let fetchRequest = CNContactFetchRequest(keysToFetch: keys)
                try contactStore.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (contact: CNContact, _) -> Void in
                    for phoneNoLab in contact.phoneNumbers {
                        if let phoneNo = phoneNoLab.value as? CNPhoneNumber,
                        normalizedPhoneNumber = PhoneNumberNormalizer.normalizePhoneNumber(phoneNo.stringValue) {
                            let pbc = PhonebookContact(contactID: contact.identifier, phoneNumber: normalizedPhoneNumber)
                            contacts.append(pbc)
                        }
                    }
                })
            }
            catch {
                NSLog("Unable to fetch contacts.")
            }
        }
    }
    return contacts
}

稍后通过标识符再次访问某个联系人是通过以下方式完成的:

class func getContactNameByUUID(identifier: String) -> String?{
    var name : String?
    PhoneBookContactsHelper.requestForAccess()
        { (accessGranted) -> Void in
            if accessGranted {
                let contactStore = CNContactStore()
                let keys = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)]
                do {
                    let cnc = try contactStore.unifiedContactWithIdentifier(identifier, keysToFetch: keys)
                    name = CNContactFormatter.stringFromContact(cnc, style: .FullName)!
                }
                catch _ {
                    NSLog("Could not fetch contact with id \(identifier))")
                }
            }
    }
    return name
}

我正在使用 iOS 9 并在模拟器和各种 iPhone 上进行了测试,意外的行为随处可见。

4

0 回答 0