Get iOS contact image with ABPersonCopyImageData

帅比萌擦擦* 提交于 2019-11-29 12:07:44

Same problem that I faced in my project earlier. Try this,

//To Get image

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

//To set image in your ImageView

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

The AddressBook framework is one of the frameworks that is really nasty to use with Swift. First I'll point out that there is a new Contacts framework in iOS 9, which I would suggest you use if you have the option of not supporting 8 and earlier (AddressBook is deprecated as of iOS 9).

Having said that, the function ABPersonCopyImageData(ABRecord!) returns a value that has the type Unmanaged<CFData>!, which means that it is possible that it will be a nil value (it really should be Unmanaged<CFData>?, but I think Apple didn't bother fixing up AddressBook types because they were working on the Contacts framework instead. Given that it can and will return nil, you'll need to treat it like it could be nil even though it is an implicitly unwrapped type.

Change:

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

to:

let imagemContato: UIImage?
if let data = ABPersonCopyImageData(person)?.takeRetainedValue() as? NSData     {
    imagemContato = UIImage(data: data)
}
else {
    imagemContato = nil
}

Note: Later on in your code you force unwrap imagemContato when you create your Contato instance. You will have to handle the case where it is a nil value or your program will potentially crash when you do this.

i solved it using

        let imagemContato: UIImage?
        let imgData: CFData?

        if ABPersonHasImageData(person) {
            imgData = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail).takeRetainedValue()
            imagemContato = UIImage(data: imgData!)
        }else{
            //placeholder
            imagemContato = UIImage(named: "UooQo.jpg")
        }

is this the correct way?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!