小编典典

使用ABPersonCopyImageData获取iOS联系人图像

swift

我正在尝试阅读我的iOS通讯录的联系人图像,但遇到了一些
麻烦。

我有一个读取ABAddressBookRef的联系人信息
并将其放在结构上的方法。

func readContacts(addressBook: ABAddressBookRef){
        let allPeople = ABAddressBookCopyArrayOfAllPeople(addressBookRef).takeRetainedValue() as NSArray
        var numeros : [Numeros] = []

        //lendo todos os contatos
        for person: ABRecordRef in allPeople{

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

            let phones : ABMultiValueRef = ABRecordCopyValue(person, kABPersonPhoneProperty).takeUnretainedValue() as ABMultiValueRef

            let data = ABPersonCopyImageData(person).takeRetainedValue() as NSData
            let imagemContato = UIImage(data: data)

            for(var numberIndex : CFIndex = 0; numberIndex < ABMultiValueGetCount(phones); numberIndex++) {
                let phoneUnmaganed = ABMultiValueCopyValueAtIndex(phones, numberIndex)

                let phoneNumber : NSString = phoneUnmaganed.takeUnretainedValue() as! NSString

                let locLabel : CFStringRef = (ABMultiValueCopyLabelAtIndex(phones, numberIndex) != nil) ? ABMultiValueCopyLabelAtIndex(phones, numberIndex).takeUnretainedValue() as CFStringRef : ""

                let cfStr:CFTypeRef = locLabel
                let nsTypeString = cfStr as! NSString
                let swiftString:String = nsTypeString as String

                //let customLabel = String (stringInterpolationSegment: ABAddressBookCopyLocalizedLabel(locLabel))

                let numero: Numeros = Numeros(tipoNumero: swiftString, numero: phoneNumber as String)

                numeros.append(numero)

            }

            let registroContato: Contato = Contato(primeiroNome: firstName, ultimoNome: lastName, contatoRecord: person, numeros: numeros, imagemContato: imagemContato!)

            contatos.append(registroContato)

        }
    }

but when I debug it, it stops on:

let data = ABPersonCopyImageData(person).takeRetainedValue() as NSData

并且不显示任何错误消息。

我究竟做错了什么?

我正在使用模拟器的默认联系人对其进行测试,他们没有图像,
但是有占位符及其名字的第一个字母。

编辑:

我将代码更改为

let imagemContato: UIImage?
            if let data = ABPersonCopyImageData(person)?.takeRetainedValue() as? NSData     {
                print("\(firstName) with image")
                imagemContato = UIImage(data: data)
            }
            else {
                print("\(firstName) without image")
                imagemContato = UIImage(named: "UooQo.jpg")
            }

并且在控制台上,所有联系人都没有图像:

控制台输出:凯特(Kate)没有图像丹尼尔(Daniel)没有图像约翰(John)没有图像
安娜(Anna)没有图像汉克(Hank)没有图像大卫(David)没有图像


阅读 268

收藏
2020-07-07

共1个答案

小编典典

我之前在项目中遇到的同样问题。试试这个,

//获取图片

   let img = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail).takeRetainedValue()

//在ImageView中设置图像

YourImageView.image=UIImage(data: img as! NSData)
2020-07-07