I need to convert my Objective-C to Swift to get an image of a contact from the Address Book. But I get an error with for cast from CFData
to NSData
and I don't know how make this work. What can I do to make this work correctly?
In Objective-C:
ABRecordID contactID = ABRecordGetRecordID(contactRef);
ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordRef origContactRef = ABAddressBookGetPersonWithRecordID(addressBook, contactID);
if (ABPersonHasImageData(origContactRef)) {
NSData *imgData = (NSData*)ABPersonCopyImageDataWithFormat(origContactRef, kABPersonImageFormatOriginalSize);
img = [UIImage imageWithData: imgData];
[imgData release];
}
CFRelease(addressBook);
return img;
In Swift:
var image: UIImage!
if ABPersonHasImageData(person) {
var imgData = (ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize))
image = UIImage.imageWithData(imgData) //Here get the error
}
As explained in
Working with Cocoa Data Types, you have to convert the unmanaged object to a memory managed object with takeUnretainedValue()
or takeRetainedValue()
.
In your case
if (ABPersonHasImageData(person)) {
let imgData = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize).takeRetainedValue()
let image = UIImage(data: imgData)
}
because ABPersonCopyImageDataWithFormat()
returns a (+1) retained value.
if let imgData = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize)?.takeUnretainedValue() {
if let image = UIImage(data: imgData) {
//Here's your UIImage
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With