Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert unmanaged<CFData> to NSData?

Tags:

swift

xcode6

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 
}
like image 483
user3745888 Avatar asked Aug 12 '14 10:08

user3745888


2 Answers

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.

like image 102
Martin R Avatar answered Sep 27 '22 15:09

Martin R


if let imgData = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize)?.takeUnretainedValue() {
   if let image = UIImage(data: imgData) {
      //Here's your UIImage
   }
}
like image 36
Adam Lovastyik Avatar answered Sep 27 '22 17:09

Adam Lovastyik