ABAddressBook fromOpaque(_:) in Swift 3

ABAddressBook fromOpaque(_:) in Swift 3

所以我刚刚更新到 Xcode 8 并将我的 Swift 2.3 代码转换为 Swift 3,我在这行代码中有一个错误不是在 Swift 2.3:

func populateFrom(_ addressBook:ABAddressBook)
{
    let allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue()
    let nPeople = ABAddressBookGetPersonCount(addressBook)
    for index in 0..<nPeople
    {
       let person:ABRecord = Unmanaged<ABRecord>.fromOpaque(OpaquePointer(CFArrayGetValueAtIndex(allPeople, index))).takeUnretainedValue()
    }
}

现在问题在行let person:ABRecord = Unmanaged<ABRecord>.fromOpaque(OpaquePointer(CFArrayGetValueAtIndex(allPeople, index))).takeUnretainedValue()

Xcode 告诉我 'fromOpaque' is unavailable: use 'fromOpaque(_:UnsafeRawPointer)' instead。但是我找不到那个函数 Xcode 告诉我使用,我只能找到 fromOpaque(value: UnsafeRawPointer) 这是我目前正在使用的那个。

我怎样才能使这个工作?

您可以稍微简化一下,消除所有那些不透明的指针引用,例如:

func populate(from addressBook: ABAddressBook) {
    let allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as [ABRecord]
    for person in allPeople {
        let name = ABRecordCopyCompositeName(person).takeRetainedValue()
        print(name)
    }
}

或者,鉴于 AddressBook 框架在 iOS 9 中已被弃用,您可以使用联系人框架:

let store = CNContactStore()
store.requestAccess(for: .contacts) { granted, error in
    guard granted else {
        print(error)
        return
    }

    self.populate(from: store)
}

func populate(from store: CNContactStore) {
    let formatter = CNContactFormatter()
    formatter.style = .fullName

    let request = CNContactFetchRequest(keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: formatter.style)])
    do {
        try store.enumerateContacts(with: request) { contact, stop in
            print(formatter.string(from: contact))
        }
    } catch {
        print(error)
    }
}