14

我需要从 AddressBook 框架转换此函数的返回值:

ABRecordCopyValue(nil, kABPersonPhoneProperty)

到 ABMultiValueRef 类型的值

此功能目前标记为:

func ABRecordCopyValue(record: ABRecordRef!, property: ABPropertyID) -> Unmanaged<AnyObject>!

所以我可以像这样将它转换为非托管:

ABRecordCopyValue(person, kABPersonPhoneProperty) as Unmanaged<ABMultiValueRef>

但是我怎样才能得到它作为 ABMultiValueRef 以便我可以将它传递给这个函数呢?

func ABMultiValueGetIndexForIdentifier(multiValue: ABMultiValueRef!, identifier: ABMultiValueIdentifier) -> CFIndex

我这样做了:

let managedPhones = Unmanaged.fromOpaque(phones.toOpaque()).takeUnretainedValue() as ABMultiValueRef

而且我不断收到此编译器错误:

Bitcast requires both operands to be pointer or neither
%89 = bitcast %objc_object* %88 to %PSs9AnyObject_, !dbg !325
LLVM ERROR: Broken function found, compilation aborted!
Command /Applications/Xcode6-Beta3.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 1
4

3 回答 3

25

我找到了解决方案:

func peoplePickerNavigationController(
  peoplePicker: ABPeoplePickerNavigationController!,
  didSelectPerson person: ABRecordRef!) {

    /* Do we know which picker this is? */
    if peoplePicker != personPicker{
      return
    }

    /* Get all the phone numbers this user has */
    let unmanagedPhones = ABRecordCopyValue(person, kABPersonPhoneProperty)
    let phones: ABMultiValueRef =
    Unmanaged.fromOpaque(unmanagedPhones.toOpaque()).takeUnretainedValue()
      as NSObject as ABMultiValueRef

    let countOfPhones = ABMultiValueGetCount(phones)

    for index in 0..<countOfPhones{
      let unmanagedPhone = ABMultiValueCopyValueAtIndex(phones, index)
      let phone: String = Unmanaged.fromOpaque(
        unmanagedPhone.toOpaque()).takeUnretainedValue() as NSObject as String

      println(phone)
    }  
}
于 2014-07-26T14:01:49.707 回答
1

如果有人正在寻找在 Swift 2 中处理 ABRecords 的最终方法,这里是:

func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord) {

    let firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty).takeRetainedValue()
    let lastName = ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue()

    var emails:[String] = []
    let emailRecords = ABRecordCopyValue(person, kABPersonEmailProperty).takeRetainedValue() as ABMultiValueRef
    let emailsCount = ABMultiValueGetCount(emailRecords)
    for index in 0 ..< emailsCount {
        if let email = ABMultiValueCopyValueAtIndex(emailRecords, index).takeRetainedValue() as? String {
            emails.append(email)
        }
    }

    print("Contact selected. firstName: \(firstName), lastName: \(lastName), emails: \(emails)")

}
于 2016-07-14T10:57:11.220 回答
0

和我一样,这可能是编译器问题。如果你也想关注我的帖子ABPeoplePickerNavigationController shouldContinueAfterSelectingPerson 已弃用 Swift

于 2014-07-21T21:55:50.320 回答